Compare commits

...
269 Commits
Author SHA1 Message Date
Arty Bishop 1156824463 v2.6.0 - Minor fixes release, closed issues #77 and #80 2022-01-09 17:39:37 +00:00
Arty Bishop f48a46d0e4 Fixed csv data parser bug, now showing correct data 2022-01-08 12:29:16 +00:00
Arty Bishop 738aa1132a v2.5.9 - Hotfix for update crash 2021-12-11 15:00:20 +00:00
Arty Bishop 80e49ad85a v2.5.8 - Fixed update crash, redundant components removed 2021-12-10 08:27:12 +00:00
Arty Bishop f9c4650ace Restored missing app icons for low-res/api screens 2021-12-05 12:08:04 +00:00
Arty Bishop 891721bf45 Extensions.kt cleanup, dependencies update 2021-11-28 12:17:00 +00:00
Arty Bishop f694eb4f4d Info layout fixes, text input outline color fix 2021-11-20 12:35:58 +00:00
Arty Bishop f3257660ca Bottom bar text size, map zoom level, pass ripple fixes 2021-11-18 12:27:43 +00:00
Arty Bishop 7f5d205e4b Simplified satellite entry item layout, enabled R8 full mode 2021-11-17 19:40:26 +00:00
Arty Bishop 524a791629 Matched CSV and TLE parsed epoch and eccentricity data 2021-11-16 18:07:56 +00:00
Arty Bishop 1d0716d47f Removed redundant material components 2021-11-09 14:56:05 +01:00
Arty Bishop 04029d50db Added RemoteSource.kt exception catch, dependencies update 2021-11-09 11:48:29 +01:00
Arty Bishop 5ba7ee746c v2.5.7 - Fixed checkbox bug and github actions regression 2021-10-29 19:07:18 +01:00
Arty Bishop a6f772f4de Fixed satellite selection checkbox click bug 2021-10-29 18:32:15 +01:00
Arty Bishop f8f7aba3a8 v2.5.6 - APIv21, issues #68 #69, grid layout, async update 2021-10-28 21:46:02 +01:00
Arty Bishop 88c7bb6bca Removed all java dependencies from domain.predict package 2021-10-28 19:32:21 +01:00
Arty Bishop 8ef0d103e4 Added ability to toggle from pass view to map view #68 2021-10-27 21:47:02 +01:00
Arty Bishop 96ae6338a7 Fixed Redmi dark theme colors bug, minor layouts cleanup 2021-10-27 21:47:02 +01:00
Arty Bishop 9b76d42707 Fetching satellite data asynchronously, increased build speed 2021-10-27 21:47:02 +01:00
Arty Bishop 5998a7e66d Added DataParser.kt with tests, removed unused classes 2021-10-27 21:47:02 +01:00
Arty Bishop c8f7a29812 Swapped RetrofitRemoteSource.kt for a simplified one 2021-10-27 21:47:02 +01:00
Arty Bishop 13f1cc6455 Added OMM to TLE conversion function 2021-10-27 21:47:02 +01:00
Arty Bishop bf72cd2061 Further code refactoring and cleanup 2021-10-27 21:47:02 +01:00
Arty Bishop 253321f3c2 Added database migration, removed moshi and Converters.kt 2021-10-27 21:47:02 +01:00
Arty Bishop 9baaf38a49 Minor strings fixes
Everything seems great, just slightly adjusted the strings variables to avoid any conflict with the Ru locale. I'll add the proper translation with the feature fully implemented and v2.5.6 release.
2021-10-27 21:47:02 +01:00
Kamil Wargula 5c5f08afc0 Add notification button and dialog on Radar Fragment 2021-10-27 21:47:02 +01:00
Arty Bishop 5f4c63ee49 Moved sources urls to database storage 2021-10-27 21:47:02 +01:00
Arty Bishop af7e027350 Switched to GridLayoutManager in entries recycler, classes moved 2021-10-27 21:47:02 +01:00
Arty Bishop db8fe3ce8d Fixed antenna rotator control issue #69 2021-10-27 21:47:02 +01:00
Arty Bishop 55a827330f Moved and renamed several classes 2021-10-27 21:47:02 +01:00
Arty Bishop 6fa63fdcff Added coroutine exception handler to EntriesViewModel.kt 2021-10-27 21:47:02 +01:00
Arty Bishop b6d019ace7 Renamed and moved several classes and interfaces 2021-10-27 21:47:02 +01:00
Arty Bishop 84240c94c6 Added frequency reporting to PassReporter.kt 2021-10-27 21:47:02 +01:00
Arty Bishop 09f35579dc Switched to SplashScreen API 2021-10-27 21:47:02 +01:00
Arty Bishop 8c7e2c9bb0 Extracted rotation data reporting to a separate class 2021-10-27 21:47:02 +01:00
Arty Bishop f3d64d23b2 Reverted API version to v21, Android 5.0 2021-10-27 21:47:02 +01:00
Arty Bishop 37ede31227 v2.5.5 - Fixed data update crash, issues #66 and #67 2021-10-27 21:47:01 +01:00
Arty Bishop 08b4274ca2 Now correctly using the hours ahead setting #66 2021-09-18 17:03:42 +01:00
Arty Bishop fa0f300dcd Fixed broken pass progress indicator #67 2021-09-18 17:03:41 +01:00
Arty Bishop 1fafd04190 Moved and renamed several classes 2021-09-18 16:48:05 +01:00
Arty Bishop f295b3b224 Fully extracted satellite data calculation to Predictor class 2021-09-18 12:41:41 +01:00
Arty Bishop e6d0671816 v2.5.4 - Added radar sweep animation, fixed update issue 2021-09-17 10:10:20 +01:00
Arty Bishop 4bf2e6c768 Added database migration and schema export, fixed crash 2021-09-17 09:49:12 +01:00
Arty Bishop 94751519ac Moved and refactored several classes 2021-09-16 10:33:21 +01:00
Arty Bishop 673474a51f Removed redundant StationPos.kt class 2021-09-16 10:14:18 +01:00
Arty Bishop a82915c0ca Further changes to Look4Sat Predictor.kt core class 2021-09-16 10:03:58 +01:00
Arty Bishop bceeb01194 Further refactoring of Look4Sat core module classes 2021-09-15 09:58:40 +01:00
Arty Bishop 2c757a6b35 Added unit tests for sat params parsing 2021-09-12 15:40:05 +01:00
Arty Bishop 9a4de03cac Renamed and refactored several predict4kotlin classes 2021-09-12 12:21:23 +01:00
Arty Bishop c38fe8b10f Bumped SDK version, further changes to predict4kotlin 2021-09-10 17:33:42 +01:00
Arty Bishop 60a67f86b6 Moved TLE import and Satellite creation to TLE companion object 2021-09-08 18:07:04 +01:00
Arty Bishop ae21e9e5ca Further changes to predict4kotlin classes 2021-09-06 22:39:10 +01:00
Arty Bishop 964fdfbc05 Set exported flag to AndroidManifest.xml 2021-09-05 20:40:30 +01:00
Arty Bishop dc92bf1ab1 Various changes to predict4kotlin classes 2021-09-05 20:36:50 +01:00
Arty Bishop 5460ed2a6c Added PassInfoView.kt radar sweep animation 2021-09-05 19:39:50 +01:00
Arty Bishop 187791f895 Reverted item_pass_leo.xml, updated Extensions.kt 2021-09-04 14:23:13 +01:00
Arty Bishop 0638539f3c Dependencies update, gradle version bumped 2021-08-28 14:05:58 +01:00
Yuhui Su 69d256e008 Fixed the overlapping and blocked texts on the "passes" page #65
* fixed the blocked time string
* fixed the overlapped texts for items on the 'passes' page
2021-08-23 12:25:33 +01:00
Arty Bishop d603a343ca Bumped minSdk to 23 (Android 6.0), fixed AMSat SSL issue 2021-06-20 14:50:29 +01:00
Arty Bishop a26f881160 Dependencies update, fixed issue #58 2021-05-31 09:42:31 +01:00
Arty Bishop eb1ac3341f v2.5.2 - Fixed aiming icon issue #57 and list scrolling issue #59 2021-05-19 09:39:01 +01:00
Arty Bishop ae1fbb1687 Fixed tle update triggered crash 2021-05-19 09:35:52 +01:00
Arty Bishop a0a95ce372 Reverted TLE source update screen, fixed location setting bug #53 #54 2021-05-18 10:24:26 +01:00
Arty Bishop fb2008b07a v2.5.0 - Minor fixes, updated screenshots, version bumped 2021-05-17 09:53:34 +01:00
Arty Bishop 74528f4a14 Added missing copyright notice 2021-05-16 19:33:20 +01:00
Arty Bishop 2d45fd614e Added pass direction arrow to radar view #52 2021-05-16 19:13:11 +01:00
Arty Bishop 1da35e901a Added custom source TLE update dialog 2021-05-16 19:13:11 +01:00
Arty Bishop 5de8787368 Swapped the splash dialog for immediate initial setup 2021-05-16 19:13:11 +01:00
Arty Bishop e3e621e55f Removed sat icon from pass info view 2021-05-16 19:13:11 +01:00
Arty Bishop fdb5752408 Moved and renamed various classes to simplify structure 2021-05-16 19:13:11 +01:00
Arty Bishop c91c58ac69 Removed interacting use cases for the sake of code simplicity 2021-05-16 19:13:10 +01:00
Arty Bishop 0110de8104 Repositories refactoring and merge 2021-05-16 19:13:10 +01:00
Arty Bishop 1a59b5e3e1 Extracted station position management to a separate class 2021-05-16 19:13:10 +01:00
Arty Bishop 5ef79148bd Updated dependencies and gradle version 2021-05-16 19:13:10 +01:00
Arty Bishop 1806e0d147 Added mockito dependency, fixed radar view update bug #51 2021-05-16 19:13:10 +01:00
Arty Bishop 4cfab17413 Further fixes to MapFragment.kt and MapViewModel.kt 2021-04-27 21:06:37 +01:00
Arty Bishop 48758b4f3d Minor fixes to MapFragment.kt and MapViewModel.kt 2021-04-25 15:44:29 +01:00
Arty Bishop fe69e90749 Added orientation pointer to PolarView.kt, changed drawn satellite icon 2021-04-25 10:19:43 +01:00
Arty Bishop 3c29dafd51 Added OMM class for future celestrak compatibility, fixes to PolarView 2021-04-24 17:49:55 +01:00
Arty Bishop 9ffb793dfd Minor refactoring and classes move 2021-04-24 16:47:42 +01:00
Arty Bishop e9a6471b6d Implemented Clean architecture, removed redundant dependencies 2021-04-23 12:59:18 +01:00
Arty Bishop 53fcf4790a Added framework DataSources, DataMapper and Models 2021-04-23 10:19:51 +01:00
Arty Bishop 865ecfb5bf Added SatelliteRepo basic interactors 2021-04-22 13:20:42 +01:00
Arty Bishop d0569f4645 Created satellite DataSources and Repository 2021-04-22 12:50:18 +01:00
Arty Bishop 3db474c763 Created a core module, basic clean architecture setup 2021-04-21 18:27:56 +01:00
Arty Bishop 5f7c3e3786 v2.4.0 - Showing azimuth for respective maxElevation 2021-04-18 19:58:08 +01:00
Arty Bishop e27224d9a8 Added rotator ip address and port checks and error messages 2021-04-18 18:40:23 +01:00
Arty Bishop e5e5fe7ee7 Fixes to the Az-El message sent via socket to rotctld 2021-04-18 17:45:38 +01:00
Arty Bishop 18820b79f4 Removed sat track tail from the map, minor refactoring 2021-04-17 12:46:51 +01:00
Arty Bishop a205ebfa2b Added rotator control function to PolarViewModel.kt 2021-04-14 18:32:57 +01:00
Arty Bishop 703dc17794 Added rotator control preferences to settings screen 2021-04-14 18:32:57 +01:00
Arty Bishop 046ec8ee8c Removed hardcoded screen orientation and redundant network state permission from manifest 2021-04-14 18:31:57 +01:00
Arty Bishop 7cfe44ed13 Merge pull request #49 from yix/master
Add sat name to the polar view
2021-04-14 17:21:56 +01:00
Alex M 5352bd5182 Add sat name to the polar view 2021-04-10 12:08:03 -04:00
Arty Bishop db710c55c4 Fixed transmitters doppler frequency update logic 2021-04-05 19:32:07 +01:00
Arty Bishop 555c2fe626 Extracted passes ticking logic from PassesAdapter.kt 2021-04-05 12:06:06 +01:00
Arty Bishop 7b4f58dd78 Removed deprecated 'artifact' input in github workflow 2021-04-05 09:03:21 +01:00
Arty Bishop b2deab0d7c Fixed recent InflationException, version code bumped 2021-04-05 08:52:03 +01:00
Arty Bishop 39c3a69a11 Minor fixes to various classes, version code bumped 2021-04-04 20:57:50 +01:00
Arty Bishop 8c67ec4808 Extracted sensor listening logic from PolarFragment.kt to Orientation.kt 2021-04-03 17:22:01 +01:00
Arty Bishop c2216e4917 Fixed behaviour of passes recycler ticking and refreshing 2021-04-03 13:47:02 +01:00
Arty Bishop cfd1a2f2b8 Second attempt for correct passes AsyncListDiffer 2021-04-02 22:22:36 +01:00
Arty Bishop af49acf4d9 Temporarily reverted Passes AsyncDiffer 2021-04-02 21:01:53 +01:00
Arty Bishop 7e97cbea1b AsyncListDiffer try for satellite passes 2021-04-02 20:29:57 +01:00
Arty Bishop 6b3a3b31d6 Final satellite entries refactoring, hopefully 2021-03-30 21:43:20 +01:00
Arty Bishop 2044ea273b Now sorting sat items list via LiveData switchMap 2021-03-29 23:11:08 +01:00
Arty Bishop aef560942f Minor visual changes to map info 2021-03-28 17:47:20 +01:00
Arty Bishop 2ba06c779f Further modification of entries selection logic 2021-03-28 11:02:08 +01:00
Arty Bishop 040ad844f5 Now clearing satellite transceivers data on update 2021-03-27 19:32:47 +00:00
Arty Bishop 76dce66a4a Further refactoring of entries selection and filtering logic 2021-03-27 18:57:08 +00:00
Arty Bishop 8d8e0bb7ac Added sat items filtering by transmitter mode 2021-03-27 16:54:03 +00:00
Arty Bishop 995953b823 Fixed sensor error when user holds the phone upright 2021-03-26 09:16:59 +00:00
Arty Bishop e8208b7934 Added SatItem and SatTrans relation to retrieve trans modes 2021-03-26 08:40:28 +00:00
Arty Bishop de11eb98c0 Minor fix to PolarFragment.kt sensor rotation event 2021-03-25 08:53:39 +00:00
Arty Bishop a8b43ca3fb Fixed satellite track show issue, minor Map fixes 2021-03-24 10:17:10 +00:00
Arty Bishop 6f8db0b9b1 Simplified transmitters, added database migration 2021-03-23 10:28:51 +00:00
Arty Bishop a882a73b8e Simplified SatPass.kt, predictor now returns this class 2021-03-23 10:03:42 +00:00
Arty Bishop 33d25d3c25 Replaced original SatPassTime class with my own 2021-03-22 21:37:20 +00:00
Arty Bishop 37c5ebbf2e Fragments and adapters refactoring 2021-03-21 21:16:52 +00:00
Arty Bishop f04e54d59b Separated satellite map logic from the passes screen 2021-03-21 19:53:59 +00:00
Arty Bishop 332b6f666c Added several extension functions 2021-03-21 19:48:20 +00:00
Arty Bishop e0f900366a Added PolarViewModel, removed SharedViewModel 2021-03-20 17:32:26 +00:00
Arty Bishop 4edf316b5e Added PassesViewModel.kt 2021-03-20 16:44:40 +00:00
Arty Bishop d32e5a5ce3 Fixed SelectAllItems button behaviour 2021-03-20 15:34:42 +00:00
Arty Bishop 46bf23171f Switched to using the AsyncListDiffer in EntriesAdapter.kt 2021-03-20 14:36:20 +00:00
Arty Bishop ca3a9e900f Added satellite passes repository 2021-03-18 22:32:05 +00:00
Arty Bishop f370aef0a7 Created separate ViewModel for EntriesFragment.kt 2021-03-18 21:50:14 +00:00
Arty Bishop af7a4d03d2 Switched to using the NavResult Api for tle sources list 2021-03-18 21:43:30 +00:00
Arty Bishop 0ddd0286a5 Minor refactoring of EntriesAdapter.kt 2021-03-18 21:09:24 +00:00
Arty Bishop 46f1ea9880 Changes to DAO and file structure 2021-03-18 20:40:09 +00:00
Arty Bishop 31ed6230ba Swapped Entries StateFlow for SharedFlow 2021-03-17 20:47:24 +00:00
Arty Bishop c981f0900a Moved sat data update back to SharedViewModel.kt 2021-03-16 20:02:28 +00:00
Arty Bishop d013afbf50 Added isNetworkAvailable extension function 2021-03-15 18:10:05 +00:00
Arty Bishop a6d63748fb Switched to concurrent satellite data update 2021-03-15 17:42:43 +00:00
Arty Bishop 5b1bf943e9 Now using repository external scope for sat data update 2021-03-14 20:33:28 +00:00
Arty Bishop 2427f8cbf5 Added GitHub release creation to default action workflow 2021-03-12 14:22:09 +00:00
Arty Bishop cf41889017 Added release signing config 2021-03-11 22:14:04 +00:00
Arty Bishop 8134db90d6 Swapped SingleLiveEvent for MutableStateFlow 2021-03-11 21:34:57 +00:00
Arty Bishop d493e3e87b Fixed IllegalArgException on pass to polar navigation. Triggering github actions on tags push. 2021-03-09 09:33:03 +00:00
Arty Bishop c37537bd67 Added NavController navigateSafe extension function 2021-03-09 09:10:22 +00:00
Arty Bishop 62026abd71 Added deploy bundle workflow triggered on master branch push 2021-03-08 22:28:09 +00:00
Arty Bishop 41a34ce524 Added workflow badge to README.md 2021-03-07 20:19:54 +00:00
Arty Bishop 6e06e16493 Added gradlew executable bit to default workflow 2021-03-07 20:10:29 +00:00
Arty Bishop d3def31c82 Added Look4Sat CI workflow 2021-03-07 20:05:41 +00:00
Arty Bishop 6c78d17faf v2.2.1 - Hotfix for ClassCastException in SharedPrefs 2021-03-07 18:01:11 +00:00
Arty Bishop dbae12a4e4 Switched to GPL v3, added privacy policy 2021-03-07 13:19:52 +00:00
Arty Bishop 3722ec3b05 Fixed select all logic in Entries adapter 2021-03-07 11:35:34 +00:00
Arty Bishop 44910389e3 Added zipped TLE import from Mike McCants' web site 2021-03-06 18:10:15 +00:00
Arty Bishop 0dfd7e6250 Added room type converter for Satellite objects 2021-03-06 17:08:36 +00:00
Arty Bishop 4705ff6915 Using passes screen as a startDestination 2021-03-06 16:28:45 +00:00
Arty Bishop ab811e4ead Switched to SatItems in Entries recycler Adapter 2021-03-06 15:42:35 +00:00
Arty Bishop 8df2334cd6 Removed redundant data class modifiers, minor cleanup 2021-03-06 15:31:47 +00:00
Arty Bishop b169af4883 Now correctly popping back stack on PolarView pass end 2021-03-06 12:58:38 +00:00
Arty Bishop 06633625ba Back to single repo, using retrofit to fetch satellite data 2021-03-05 09:21:17 +00:00
Arty Bishop ef51f671b7 Now storing tle sources in shared prefs, restoring defaults. Added DB migration. 2021-03-03 20:58:09 +00:00
Arty Bishop a15e789e70 Added app-wide supervisor scope to CoroutinesModule.kt 2021-03-02 07:54:06 +00:00
Arty Bishop 31fe18e4b5 Using default TLE sources if empty sources list passed for update 2021-03-01 20:57:58 +00:00
Arty Bishop 07db0378c5 Fixed NullPointerException in EntriesFragment's update from file result 2021-03-01 20:47:17 +00:00
Arty Bishop 4c83cd2e21 Code refactoring, moving classes to new packages 2021-02-28 19:00:08 +00:00
Arty Bishop 4fa2f13834 Cleaned up dependencies, injecting Moshi in RoomConverters 2021-02-28 18:58:54 +00:00
Arty Bishop decc24ea2a v2.1.0 - Various fixes, version code bumped 2021-02-28 13:23:49 +00:00
Arty Bishop 38d21b98a0 Swapped the onboarding activity for a simple dialog 2021-02-28 13:05:38 +00:00
Arty Bishop 7d970b9287 Added DispatchersModule.kt and CoroutineTestRule.kt for coroutine dispatchers injection 2021-02-27 17:33:01 +00:00
Arty Bishop 386c087946 Switched to using the new Activity Result API 2021-02-27 17:14:13 +00:00
Arty Bishop bfeeff5372 Cleaned up the code in PassPredictor class 2021-02-27 14:47:26 +00:00
Arty Bishop 7be9965352 Removed deprecated permission request handler 2021-02-27 11:44:41 +00:00
Arty Bishop f6ca069896 Fixed issue #44, now accepting all valid locators 2021-02-27 11:03:35 +00:00
Arty Bishop 68fbd4fc1a Added several utility extension functions 2021-02-27 09:56:08 +00:00
Arty Bishop a8f3c5eb77 Using liveData builder for appTimer, hilt update 2021-02-26 19:15:47 +00:00
Arty Bishop c929e94d0e Switched to using Kotlin Flow in repository, zoom fix 2021-02-26 18:54:46 +00:00
Arty Bishop 271719c651 Fixed satellite selection clearing bug #46 2021-02-26 18:39:11 +00:00
Arty Bishop bf1ce64553 Stopped clearing satellite entries on each TLE update #39 2021-02-26 18:36:08 +00:00
Arty Bishop 9199765c61 Now setting a correct min zoom level in MapFragment.kt #42 2021-02-26 18:29:43 +00:00
Arty Bishop 124def913a Planted a debug tree with Timber 2021-02-26 18:19:01 +00:00
Arty Bishop 0c961005fc Using native OSM LatLon clipping functions 2021-02-26 17:57:17 +00:00
Arty Bishop c06b54a3c3 Added continuous horizontal map scrolling #41 2021-02-26 17:54:41 +00:00
Arty Bishop 0438b8a51f Removed redundant interfaces, simplified the code 2021-02-25 21:07:31 +00:00
Arty Bishop 02dd0a5a78 Added QthConverter.kt class and unit tests 2021-02-25 20:50:53 +00:00
Arty Bishop 68f124ca98 Removed redundant FastLane files 2021-02-25 20:42:01 +00:00
Arty Bishop f1a78a1f47 Dependencies update 2021-02-25 20:38:06 +00:00
Arty Bishop b2285a691d v2.0.1 - Timer font reverted, version code bumped 2020-12-01 23:50:43 +00:00
Arty Bishop 791a9c206f Reverted LED type font to the regular bold one 2020-12-01 23:13:55 +00:00
Arty Bishop 2ec3826d63 Update README.md 2020-11-29 18:03:29 +00:00
Arty Bishop 24ab1b0990 v2.0.0 - New BottomNavigation UI, OSM MapView, major code refactoring 2020-11-29 17:36:43 +00:00
Arty Bishop 44497b8c3d Fixes to strings.xml, new screenshots, app description and README.md 2020-11-29 17:10:04 +00:00
Arty Bishop c58997460c Added show text labels on the map switch to preference.xml 2020-11-28 18:35:54 +00:00
Arty Bishop f055d96e5a Further changes to MapViewModel.kt, removed bottomNav ripple effect 2020-11-28 16:46:11 +00:00
Arty Bishop 4556d2d975 Further refactor of MapFragment.kt and MapViewModel.kt 2020-11-28 13:56:03 +00:00
Arty Bishop 62f8a4a534 Minor fixes to resources and UI 2020-11-27 23:34:04 +00:00
Arty Bishop e9eba47429 Added more satellite info to the MapFragment.kt 2020-11-27 17:05:51 +00:00
Arty Bishop 2fac5814d8 Changed FABs to normal size, removed old screenshots 2020-11-26 21:19:20 +00:00
Arty Bishop b850c7a41d Added MapViewModel.kt, cleaned up MapFragment.kt 2020-11-26 19:27:46 +00:00
Arty Bishop 19a0649cb3 Added satellite selection buttons to MapFragment.kt 2020-11-26 13:07:02 +00:00
Arty Bishop 59771bd0b3 Minor changes to view holders and PolarFragment.kt 2020-11-25 21:58:51 +00:00
Arty Bishop fde0159a21 Changed GEO sat item view holder 2020-11-25 21:29:11 +00:00
Arty Bishop 4c3731c23e Removed possible leak in PassesFragment.kt 2020-11-25 21:02:44 +00:00
Arty Bishop 4f206abdc6 Now resetting the AOS timer on passes recalculation 2020-11-25 20:42:35 +00:00
Arty Bishop 45b51ad65a Changed LEO sat item view holder 2020-11-25 20:21:36 +00:00
Arty Bishop 2fbb2a2733 Packages and classes renaming 2020-11-24 21:25:26 +00:00
Arty Bishop b91a7c1ff8 Finished splash activity and UI 2020-11-24 14:39:33 +00:00
Arty Bishop e524a62b77 Libs and gradle wrapper update, build.gradle cleanup 2020-11-24 14:34:44 +00:00
Arty Bishop e391ef6109 Added station location entry from QTH locator 2020-11-20 12:37:15 +00:00
Arty Bishop 328810fccf Removed unnecessary permissions from Manifest 2020-11-20 11:31:00 +00:00
Arty Bishop 2d898f1c7b Changed default snackbar style 2020-11-20 10:20:36 +00:00
Arty Bishop 8d123441b1 Added fine location permission check 2020-11-19 20:46:37 +00:00
Arty Bishop 58839c3714 Added basic onboarding activity 2020-11-19 15:18:14 +00:00
Arty Bishop 64357697bd Restored the splash theme/screen 2020-11-18 11:41:43 +00:00
Arty Bishop e59cf9e58a Removed adapter leaks in EntriesFragment.kt 2020-11-17 20:32:40 +00:00
Arty Bishop e5b9c7a132 Added LeakCanary library, removed Write_Ext_Storage permission as obsolete 2020-10-28 21:40:03 +00:00
Arty Bishop b7f7f0b477 Cleaned up the MapFragment.kt, changed satTrack color 2020-10-28 21:38:20 +00:00
Arty Bishop ca92f8581e Added Maidenhead locator conversion functions and tests #2 2020-10-27 08:12:49 +00:00
Arty Bishop e06b1bcb11 Cleaned up preference.xml, added setPositionFromGPS button 2020-10-26 22:35:37 +00:00
Arty Bishop cfdba41ed5 Using action navigating to sources dialog, removed unnecessary scopes 2020-10-25 20:07:11 +00:00
Arty Bishop a7eb805f6d Calculating doppler only for active leo satellites. Fixes to EntriesFragment states, etc. 2020-10-24 23:21:23 +01:00
Arty Bishop 7eb388f63a Navigating to SourcesDialog.kt using Jetpack Navigation 2020-10-24 21:32:20 +01:00
Arty Bishop 04fc4fd3aa Added a "buy me a coffee" button to InfoFragment.kt 2020-10-24 20:26:38 +01:00
Arty Bishop 1c766abd24 Changes to strings.xml and InfoFragment.kt 2020-10-19 23:17:09 +01:00
Arty Bishop 9930fc9bde Showing error message in passes fragment when no satellites selected 2020-10-18 21:05:32 +01:00
Arty Bishop 628a01b530 Added entries update states and error handling 2020-10-18 20:40:58 +01:00
Arty Bishop e9424ad997 Now showing progress bar while calculating passes 2020-10-18 15:22:13 +01:00
Arty Bishop 8b1901fd48 Removed safeargs plugin as it's not being used 2020-10-18 14:53:45 +01:00
Arty Bishop 0a124a36e6 Added polar fragment aos/los timer 2020-10-18 12:31:27 +01:00
Arty Bishop 8eb551fde6 Minor fixes 2020-10-18 11:37:01 +01:00
Arty Bishop ad073724cb Changes to bottom navigation menu icons 2020-10-17 21:39:06 +01:00
Arty Bishop 68bae19b1a Changes to SourcesDialog and adapter 2020-10-17 21:13:15 +01:00
Arty Bishop 810fa5b85c Optimized transmitters adapter, changes to the recycler and ViewHolders 2020-10-17 19:48:28 +01:00
Arty Bishop 69b3e4f70b Added custom recycler divider, further changes to ViewHolders 2020-10-17 14:52:19 +01:00
Arty Bishop 1c6d22ccf9 Changes to LEO sat ViewHolder 2020-10-14 22:41:01 +01:00
Arty Bishop 886a27b016 Even further changes to layout components and colors 2020-10-14 19:35:14 +01:00
Arty Bishop 5dba44c1db Further changes to the theme and colors 2020-10-13 20:11:03 +01:00
Arty Bishop 54e03e1de2 Wrapper and dependencies update 2020-10-12 23:46:25 +01:00
Arty Bishop 2413ec2be1 Fixed OSM latitude error crash 2020-10-12 23:46:24 +01:00
Arty Bishop 4e9b312ae5 Cleared colors and styles, basic application-wide dark theme setup 2020-10-12 22:45:21 +01:00
Arty Bishop b071131ba3 Colors, styles and resources cleanup 2020-10-11 23:16:58 +01:00
Arty Bishop 57eb0a7a38 Added Event.kt class for exceptions handling and showing 2020-10-10 22:30:24 +01:00
Arty Bishop 753a3c823f Fixed too many sql error on selection update 2020-10-10 21:47:44 +01:00
Arty Bishop c6aae706f9 Removed pass prefs dialog, strings cleanup 2020-10-10 16:54:40 +01:00
Arty Bishop 6631f1e745 Moved pass prefs to preferences screen 2020-10-10 16:54:40 +01:00
Arty Bishop 46e92424d4 Swapped the passes countdown timer for the coroutine LiveData trigger 2020-10-10 16:54:40 +01:00
Arty Bishop 648da0094a Now updating sources and entries on first launch 2020-10-10 16:54:40 +01:00
Arty Bishop d776b87232 Dependencies cleanup and update 2020-10-10 16:54:40 +01:00
Arty Bishop 81074941b0 Switched to multiple repositories 2020-10-10 16:54:40 +01:00
Arty Bishop 1c7ce3f726 Switched from Dagger to android Hilt DI 2020-10-10 16:54:40 +01:00
Arty Bishop 4e0aa1481b Optimized PassesAdapter and ViewHolders 2020-10-06 23:24:17 +01:00
Arty Bishop 0ba26d4d75 Now triggering passes calculation on PassesFragment start 2020-10-06 23:24:17 +01:00
Arty Bishop c4abf214f6 Now observing transmitters as LiveData from the database 2020-10-06 23:24:17 +01:00
Arty Bishop 71c9e2c298 Fixed moshi transmitter adapter issue 2020-10-06 23:24:17 +01:00
Arty Bishop 0ef2a09e8a Restored entries selection restoration =) 2020-10-06 23:24:17 +01:00
Arty Bishop 63a759e499 Created additional fastlane files 2020-10-06 23:24:17 +01:00
Arty Bishop 52c77181c8 Removed unused resources and strings 2020-10-06 23:24:17 +01:00
Arty Bishop ad194ba5df Switched from Gson to Moshi converter, removed OkHttp dependency 2020-10-06 23:24:17 +01:00
Arty Bishop 75374ca4d9 Further code cleanup, injected PrefsManager, libs update 2020-10-06 23:24:17 +01:00
Arty Bishop 1d753ba81f Restored passes calculation functionality 2020-10-06 23:24:17 +01:00
Arty Bishop e38ee6384e Fixed SourcesDialog behaviour, code cleanup 2020-10-06 23:24:17 +01:00
Arty Bishop f89a462216 Fixed satellite entries search behaviour 2020-10-06 23:24:17 +01:00
Arty Bishop 747a7620b0 Moved the unnecessary code out of MainActivity.kt 2020-10-06 23:24:17 +01:00
Arty Bishop 3935765491 Added entries recycler item divider, further fixes to the UI 2020-10-06 23:24:17 +01:00
Arty Bishop 704dac6a75 Added view rotation animator extension to Utilities.kt 2020-10-06 23:24:17 +01:00
Arty Bishop 8164384498 Added PassPrefs object, cleaned up the code in SharedViewModel and PrefsManager 2020-10-06 23:24:17 +01:00
Arty Bishop 6b39a6759a Further code refactoring in Repository.kt and EntriesFragment.kt 2020-10-06 23:24:16 +01:00
Arty Bishop 58fe352e30 Restored SourcesDialog and FileDialog in EntriesFragment 2020-10-06 23:24:16 +01:00
Arty Bishop 41cf2f3a5d Moved the "keep screen on" attr from activity to layouts 2020-10-06 23:24:16 +01:00
Arty Bishop a7bccd3b53 Added several utility extension functions, further code cleanup 2020-10-06 23:24:16 +01:00
Arty Bishop f943268035 Removed unnecessary preferences and keys 2020-10-06 23:24:16 +01:00
Arty Bishop 3cd8516d88 Added main timer font. Changes to layouts and resources. 2020-10-06 23:24:16 +01:00
Arty Bishop 4b050e21f0 Further refactoring and code cleanup 2020-10-06 23:24:16 +01:00
Arty Bishop b87f2a6e72 Code refactoring, move and cleanup 2020-10-06 23:24:16 +01:00
Arty Bishop d4ac615a8d Added NavActivity as a future replacement for the MainActivity 2020-10-06 23:24:16 +01:00
Arty Bishop 9e557ebcf5 Added ISS passes issue screenshots 2020-10-06 23:22:48 +01:00
234 changed files with 8844 additions and 7103 deletions

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
name: Look4Sat CI
on:
push:
tags:
- '*'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout latest commit
uses: actions/checkout@v2
- name: Setup java environment
uses: actions/setup-java@v1
with: { java-version: 11 }
- name: Assemble APK and Bundle
run: |
chmod +x ./gradlew
./gradlew assembleRelease
./gradlew bundleRelease
- name: Sign APK
uses: r0adkll/sign-android-release@v1
id: sign_apk
with:
releaseDirectory: app/build/outputs/apk/release
signingKeyBase64: ${{ secrets.KEY_STORE }}
keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
alias: ${{ secrets.KEY_ALIAS }}
keyPassword: ${{ secrets.KEY_PASSWORD }}
env:
BUILD_TOOLS_VERSION: "31.0.0"
- name: Sign Bundle
uses: r0adkll/sign-android-release@v1
id: sign_bundle
with:
releaseDirectory: app/build/outputs/bundle/release
signingKeyBase64: ${{ secrets.KEY_STORE }}
keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
alias: ${{ secrets.KEY_ALIAS }}
keyPassword: ${{ secrets.KEY_PASSWORD }}
env:
BUILD_TOOLS_VERSION: "31.0.0"
- name: Rename APK
run: |
mv ${{steps.sign_apk.outputs.signedReleaseFile}} app/build/outputs/apk/release/look4sat.apk
- name: Deploy Bundle to Play Store
uses: r0adkll/upload-google-play@v1.0.15
with:
serviceAccountJsonPlainText: ${{secrets.SERVICE_ACCOUNT_JSON}}
packageName: com.rtbishop.look4sat
track: production
whatsNewDirectory: fastlane/metadata/android/en-US/whatsnew
releaseFiles: ${{steps.sign_bundle.outputs.signedReleaseFile}}
- name: Create release
uses: ncipollo/release-action@v1
with:
artifacts: app/build/outputs/apk/release/look4sat.apk
bodyFile: fastlane/metadata/android/en-US/whatsnew/whatsnew-en-US
token: ${{ secrets.RELEASE_TOKEN }}
+7
View File
@@ -38,6 +38,9 @@ captures/
# Keystore files
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks
/*.properties
/keystore.properties
/app/keystore.jks
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
@@ -56,3 +59,7 @@ fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
/app/release/app-release.aab
/app/release/app-release.apk
/app/release/output-metadata.json
/app/release/
+584 -249
View File
@@ -1,281 +1,622 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Version 3, 29 June 2007
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
TERMS AND CONDITIONS
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
0. Definitions.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
"This License" refers to version 3 of the GNU General Public License.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
A "covered work" means either the unmodified Program or a work based
on the Program.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
1. Source Code.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
The Corresponding Source for a work in source code form is that
same work.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
2. Basic Permissions.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
13. Use with the GNU Affero General Public License.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
14. Revised Versions of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
NO WARRANTY
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
15. Disclaimer of Warranty.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
@@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
@@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+20 -21
View File
@@ -1,33 +1,32 @@
# Look4Sat: Radio satellite tracker
# Look4Sat: Satellite tracker
[![Look4Sat CI](https://github.com/rt-bishop/Look4Sat/actions/workflows/main.yml/badge.svg)](https://github.com/rt-bishop/Look4Sat/actions/workflows/main.yml)
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="80">](https://f-droid.org/packages/com.rtbishop.look4sat/)
[<img src="https://play.google.com/intl/en_gb/badges/static/images/badges/en_badge_web_generic.png" alt="Get it on Google Play" height="80">](https://play.google.com/store/apps/details?id=com.rtbishop.look4sat)
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="80">](https://f-droid.org/packages/com.rtbishop.look4sat/)
Amateur radio and weather satellite tracker and passes predictor for Android.
The very app creation and design is hugely inspired by the open-source [Gpredict](http://gpredict.oz9aec.net/) desktop satellite tracking application, created by [Alexandru Csete, OZ9AEC](https://github.com/csete) and contributors, supported by the [Libre Space Foundation](https://libre.space/).
The [Libre Space Foundation](https://libre.space/) team is also behind the epic [SatNOGS](https://satnogs.org/) project that provides an extremely easy to use [API](https://db.satnogs.org/api/) and [DB](https://db.satnogs.org/) with a huge amount of information about satellites, their telemetry and transmitters, which the app uses under the hood.
For TLE data calculation and passes prediction Look4Sat uses the mavenized version of [predict4java](https://github.com/davidmoten/predict4java) library, created by [David A. B. Johnson, G4DPZ](https://github.com/g4dpz) and [Dave Moten](https://github.com/davidmoten). Thank you guys for your hard work making this lib efficient and easy to use!
Also, I'd like to mention Dr T.S. Kelso for his invaluable contribution to the industry and for his [Celestrak](https://celestrak.com) website, that stores, updates and provides access to TLE data.
The app is built using Dagger2, Retrofit2, Kotlin and Kotlin coroutines, Architecture Components and Jetpack Navigation.
### Radio satellite tracker and pass predictor for Android, inspired by Gpredict
<p float="left">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/1.png" width="250"/>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/2.png" width="250"/>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/3.png" width="250"/>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/1.png" width="160"/>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/2.png" width="160"/>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/3.png" width="160"/>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/4.png" width="160">
</p>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/4.png" width="750">
### Track satellite passes with ease!
Thanks to the huge database provided by Celestrak and SatNOGS you have access to more than 3000 active satellites orbiting Earth. You can search the entire DB by satellite name or by NORAD catnum.
Satellite positions and passes are calculated relative to your location. To get reliable info make sure to set the observation position using GPS or QTH Locator in the Settings menu.
The application is built using Kotlin, Coroutines, Architecture Components and Jetpack Navigation. It is now and always will be completely ad-free and open-source.
## Main features:
* Calculating satellite passes for up to one week (168 hours)
* Calculating passes for the current or manually entered location
* Predicting satellite positions and passes for up to 4 days (96 hours)
* Showing the list of currently active and upcoming satellite passes
* Showing the active pass progress, polar trajectory and transceivers info
* Showing the satellite positional data, footprint and ground track on a map
* Offline first: passes predictions are made offline.
Weekly updates of TLEs and transceivers DB are recommended.
* Custom TLE data import is available via files with TXT or TLE extensions
* Offline first: calculations are made offline. Weekly update of TLE data is recommended.
+1
View File
@@ -1 +1,2 @@
/build
/release
+49 -58
View File
@@ -1,40 +1,40 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: "androidx.navigation.safeargs.kotlin"
plugins {
id "com.android.application"
id "kotlin-android"
id "kotlin-kapt"
id "dagger.hilt.android.plugin"
}
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
compileSdkVersion 31
buildToolsVersion "31.0.0"
defaultConfig {
applicationId "com.rtbishop.look4sat"
minSdkVersion 21
targetSdkVersion 29
versionCode 18
versionName '1.4.8'
resConfigs "en,ru"
targetSdkVersion 31
versionCode 260
versionName "2.6.0"
kapt {
arguments {
arg("room.schemaLocation", "$projectDir/schemas")
arg("room.incremental", "true")
arg("room.expandProjection", "true")
}
}
}
// def props = new Properties()
// file("../securityKeys.properties").withInputStream { props.load(it) }
buildTypes {
release {
// buildConfigField "String", "ApiKey", props.getProperty("apiKey")
// minifyEnabled true
// shrinkResources true
// proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
postprocessing {
removeUnusedCode true
removeUnusedResources true
@@ -43,50 +43,41 @@ android {
}
}
}
configurations {
all {
exclude module: 'commons-logging'
}
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "1.8"
jvmTarget = JavaVersion.VERSION_11.toString()
}
buildFeatures {
viewBinding = true
packagingOptions {
resources.excludes += "DebugProbesKt.bin"
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.google.android.material:material:$material_version"
implementation "androidx.appcompat:appcompat:$app_compat_version"
implementation "androidx.legacy:legacy-support-v4:$support_lib_version"
implementation project(':core')
implementation "androidx.core:core-splashscreen:$splash_screen_version"
implementation "androidx.constraintlayout:constraintlayout:$constraint_layout_version"
implementation "androidx.core:core-ktx:$ktx_version"
implementation "androidx.preference:preference:$preference_version"
implementation "androidx.navigation:navigation-fragment-ktx:$navigation_version"
implementation "androidx.navigation:navigation-runtime-ktx:$navigation_version"
implementation "androidx.navigation:navigation-ui-ktx:$navigation_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.navigation:navigation-fragment-ktx:$navigation_version"
implementation "androidx.navigation:navigation-ui-ktx:$navigation_version"
implementation "androidx.preference:preference-ktx:$preference_version"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
implementation "org.osmdroid:osmdroid-android:$osmdroid_version"
implementation "com.jakewharton.timber:timber:$timber_version"
implementation "org.osmdroid:osmdroid-android:$openStreetMap_version"
implementation "com.github.davidmoten:predict4java:$predict4java_version"
testImplementation "junit:junit:$junit_version"
testImplementation "org.mockito:mockito-android:$mockito_version"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version"
debugImplementation "com.squareup.leakcanary:leakcanary-android:$leak_canary_version"
}
@@ -0,0 +1,134 @@
{
"formatVersion": 1,
"database": {
"version": 2,
"identityHash": "555494c464b5a29285eb5493cc8aa5f6",
"entities": [
{
"tableName": "entries",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tle` TEXT NOT NULL, `catNum` INTEGER NOT NULL, `name` TEXT NOT NULL, `isSelected` INTEGER NOT NULL, PRIMARY KEY(`catNum`))",
"fields": [
{
"fieldPath": "tle",
"columnName": "tle",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "catNum",
"columnName": "catNum",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isSelected",
"columnName": "isSelected",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"catNum"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "transmitters",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`uuid` TEXT NOT NULL, `info` TEXT NOT NULL, `isAlive` INTEGER NOT NULL, `downlink` INTEGER, `uplink` INTEGER, `mode` TEXT, `isInverted` INTEGER NOT NULL, `catNum` INTEGER, PRIMARY KEY(`uuid`))",
"fields": [
{
"fieldPath": "uuid",
"columnName": "uuid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "info",
"columnName": "info",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlive",
"columnName": "isAlive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "downlink",
"columnName": "downlink",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "uplink",
"columnName": "uplink",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "mode",
"columnName": "mode",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "isInverted",
"columnName": "isInverted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "catNum",
"columnName": "catNum",
"affinity": "INTEGER",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"uuid"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "sources",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourceUrl` TEXT NOT NULL, PRIMARY KEY(`sourceUrl`))",
"fields": [
{
"fieldPath": "sourceUrl",
"columnName": "sourceUrl",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"sourceUrl"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '555494c464b5a29285eb5493cc8aa5f6')"
]
}
}
@@ -0,0 +1,134 @@
{
"formatVersion": 1,
"database": {
"version": 3,
"identityHash": "555494c464b5a29285eb5493cc8aa5f6",
"entities": [
{
"tableName": "entries",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tle` TEXT NOT NULL, `catNum` INTEGER NOT NULL, `name` TEXT NOT NULL, `isSelected` INTEGER NOT NULL, PRIMARY KEY(`catNum`))",
"fields": [
{
"fieldPath": "tle",
"columnName": "tle",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "catNum",
"columnName": "catNum",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isSelected",
"columnName": "isSelected",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"catNum"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "transmitters",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`uuid` TEXT NOT NULL, `info` TEXT NOT NULL, `isAlive` INTEGER NOT NULL, `downlink` INTEGER, `uplink` INTEGER, `mode` TEXT, `isInverted` INTEGER NOT NULL, `catNum` INTEGER, PRIMARY KEY(`uuid`))",
"fields": [
{
"fieldPath": "uuid",
"columnName": "uuid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "info",
"columnName": "info",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlive",
"columnName": "isAlive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "downlink",
"columnName": "downlink",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "uplink",
"columnName": "uplink",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "mode",
"columnName": "mode",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "isInverted",
"columnName": "isInverted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "catNum",
"columnName": "catNum",
"affinity": "INTEGER",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"uuid"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "sources",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourceUrl` TEXT NOT NULL, PRIMARY KEY(`sourceUrl`))",
"fields": [
{
"fieldPath": "sourceUrl",
"columnName": "sourceUrl",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"sourceUrl"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '555494c464b5a29285eb5493cc8aa5f6')"
]
}
}
@@ -0,0 +1,212 @@
{
"formatVersion": 1,
"database": {
"version": 4,
"identityHash": "0f08defa24a78647801005e9277faac7",
"entities": [
{
"tableName": "entries",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`isSelected` INTEGER NOT NULL, `name` TEXT NOT NULL, `epoch` REAL NOT NULL, `meanmo` REAL NOT NULL, `eccn` REAL NOT NULL, `incl` REAL NOT NULL, `raan` REAL NOT NULL, `argper` REAL NOT NULL, `meanan` REAL NOT NULL, `catnum` INTEGER NOT NULL, `bstar` REAL NOT NULL, `xincl` REAL NOT NULL, `xnodeo` REAL NOT NULL, `omegao` REAL NOT NULL, `xmo` REAL NOT NULL, `xno` REAL NOT NULL, `isDeepspace` INTEGER NOT NULL, PRIMARY KEY(`catnum`))",
"fields": [
{
"fieldPath": "isSelected",
"columnName": "isSelected",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tle.name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tle.epoch",
"columnName": "epoch",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.meanmo",
"columnName": "meanmo",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.eccn",
"columnName": "eccn",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.incl",
"columnName": "incl",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.raan",
"columnName": "raan",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.argper",
"columnName": "argper",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.meanan",
"columnName": "meanan",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.catnum",
"columnName": "catnum",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tle.bstar",
"columnName": "bstar",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.xincl",
"columnName": "xincl",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.xnodeo",
"columnName": "xnodeo",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.omegao",
"columnName": "omegao",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.xmo",
"columnName": "xmo",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.xno",
"columnName": "xno",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "tle.isDeepspace",
"columnName": "isDeepspace",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"catnum"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "transmitters",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`uuid` TEXT NOT NULL, `info` TEXT NOT NULL, `isAlive` INTEGER NOT NULL, `downlink` INTEGER, `uplink` INTEGER, `mode` TEXT, `isInverted` INTEGER NOT NULL, `catnum` INTEGER, PRIMARY KEY(`uuid`))",
"fields": [
{
"fieldPath": "uuid",
"columnName": "uuid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "info",
"columnName": "info",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlive",
"columnName": "isAlive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "downlink",
"columnName": "downlink",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "uplink",
"columnName": "uplink",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "mode",
"columnName": "mode",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "isInverted",
"columnName": "isInverted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "catnum",
"columnName": "catnum",
"affinity": "INTEGER",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"uuid"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "sources",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourceUrl` TEXT NOT NULL, PRIMARY KEY(`sourceUrl`))",
"fields": [
{
"fieldPath": "sourceUrl",
"columnName": "sourceUrl",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"sourceUrl"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '0f08defa24a78647801005e9277faac7')"
]
}
}
+7 -31
View File
@@ -1,45 +1,21 @@
<?xml version="1.0" encoding="utf-8"?><!--
~ Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
~ Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
~
~ This program is free software; you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation; either version 2 of the License, or
~ (at your option) any later version.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License along
~ with this program; if not, write to the Free Software Foundation, Inc.,
~ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.rtbishop.look4sat">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name="com.rtbishop.look4sat.Look4SatApp"
android:name=".presentation.Look4SatApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
android:theme="@style/Theme.Look4Sat.Main">
<activity
android:name="com.rtbishop.look4sat.ui.MainActivity"
android:configChanges="orientation|screenSize"
android:label="@string/app_name"
android:theme="@style/AppTheme.Splash">
android:name=".presentation.Look4SatActivity"
android:exported="true"
android:theme="@style/Theme.Look4Sat.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

@@ -1,31 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat
import android.app.Application
import com.rtbishop.look4sat.dagger.AppComponent
import com.rtbishop.look4sat.dagger.DaggerAppComponent
class Look4SatApp : Application() {
val appComponent: AppComponent by lazy {
DaggerAppComponent.factory().create(applicationContext)
}
}
@@ -1,50 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.dagger
import android.content.Context
import com.rtbishop.look4sat.dagger.modules.*
import com.rtbishop.look4sat.ui.MainActivity
import com.rtbishop.look4sat.ui.fragments.MapOsmFragment
import com.rtbishop.look4sat.ui.fragments.MapViewFragment
import com.rtbishop.look4sat.ui.fragments.PassListFragment
import com.rtbishop.look4sat.ui.fragments.PolarViewFragment
import dagger.BindsInstance
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(
modules = [NetworkModule::class, PersistenceModule::class,
RepoModule::class, UtilityModule::class, ViewModelModule::class]
)
interface AppComponent {
@Component.Factory
interface Factory {
fun create(@BindsInstance context: Context): AppComponent
}
fun inject(mainActivity: MainActivity)
fun inject(mapViewFragment: MapViewFragment)
fun inject(passListFragment: PassListFragment)
fun inject(polarViewFragment: PolarViewFragment)
fun inject(mapOsmFragment: MapOsmFragment)
}
@@ -1,25 +0,0 @@
package com.rtbishop.look4sat.dagger
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class ViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>,
@JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("Unsupported ViewModel class: $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
@@ -1,14 +0,0 @@
package com.rtbishop.look4sat.dagger
import androidx.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
@@ -1,56 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.dagger.modules
import com.rtbishop.look4sat.network.RemoteDataSource
import com.rtbishop.look4sat.network.RemoteSource
import com.rtbishop.look4sat.network.TransmittersApi
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
class NetworkModule {
@Singleton
@Provides
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient()
}
@Singleton
@Provides
fun provideRemoteDataSource(api: TransmittersApi, client: OkHttpClient): RemoteSource {
return RemoteDataSource(api, client)
}
@Singleton
@Provides
fun provideTransmittersApi(): TransmittersApi {
return Retrofit.Builder()
.baseUrl("https://db.satnogs.org/api/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(TransmittersApi::class.java)
}
}
@@ -1,71 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.dagger.modules
import android.content.Context
import androidx.room.Room
import com.rtbishop.look4sat.persistence.LocalDataSource
import com.rtbishop.look4sat.persistence.LocalSource
import com.rtbishop.look4sat.persistence.SatelliteDb
import com.rtbishop.look4sat.persistence.dao.EntriesDao
import com.rtbishop.look4sat.persistence.dao.SourcesDao
import com.rtbishop.look4sat.persistence.dao.TransmittersDao
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class PersistenceModule {
@Singleton
@Provides
fun provideEntriesDao(db: SatelliteDb): EntriesDao {
return db.entriesDao()
}
@Singleton
@Provides
fun provideTransmittersDao(db: SatelliteDb): TransmittersDao {
return db.transmittersDao()
}
@Singleton
@Provides
fun providesSourcesDao(db: SatelliteDb): SourcesDao {
return db.sourcesDao()
}
@Singleton
@Provides
fun provideLocalDataSource(
entriesDao: EntriesDao,
transmittersDao: TransmittersDao,
sourcesDao: SourcesDao
): LocalSource {
return LocalDataSource(entriesDao, transmittersDao, sourcesDao)
}
@Singleton
@Provides
fun provideSatelliteDb(context: Context): SatelliteDb {
return Room.databaseBuilder(context, SatelliteDb::class.java, "satDb")
.build()
}
}
@@ -1,31 +0,0 @@
package com.rtbishop.look4sat.dagger.modules
import android.content.ContentResolver
import android.content.Context
import com.rtbishop.look4sat.network.RemoteSource
import com.rtbishop.look4sat.persistence.LocalSource
import com.rtbishop.look4sat.repo.DefaultRepository
import com.rtbishop.look4sat.repo.Repository
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class RepoModule {
@Singleton
@Provides
fun provideContentResolver(context: Context): ContentResolver {
return context.applicationContext.contentResolver
}
@Singleton
@Provides
fun provideDefaultRepository(
resolver: ContentResolver,
localSource: LocalSource,
remoteSource: RemoteSource
): Repository {
return DefaultRepository(resolver, localSource, remoteSource)
}
}
@@ -1,54 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.dagger.modules
import android.content.Context
import android.content.SharedPreferences
import android.location.LocationManager
import androidx.preference.PreferenceManager
import com.rtbishop.look4sat.utility.PrefsManager
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class UtilityModule {
@Singleton
@Provides
fun provideSharedPreferences(context: Context): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(context)
}
@Singleton
@Provides
fun provideLocationManager(context: Context): LocationManager {
return context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
@Singleton
@Provides
fun providePrefsManager(
sharedPreferences: SharedPreferences,
locationManager: LocationManager
): PrefsManager {
return PrefsManager(sharedPreferences, locationManager)
}
}
@@ -1,22 +0,0 @@
package com.rtbishop.look4sat.dagger.modules
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.rtbishop.look4sat.dagger.ViewModelFactory
import com.rtbishop.look4sat.dagger.ViewModelKey
import com.rtbishop.look4sat.ui.SharedViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(SharedViewModel::class)
abstract fun bindSharedViewModel(viewModel: SharedViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
}
@@ -1,7 +0,0 @@
package com.rtbishop.look4sat.data
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object InProgress : Result<Nothing>()
}
@@ -1,12 +0,0 @@
package com.rtbishop.look4sat.data
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.github.amsacode.predict4java.TLE
@Entity(tableName = "entries")
data class SatEntry(val tle: TLE, var isSelected: Boolean = false) {
@PrimaryKey
var catNum: Int = tle.catnum
var name: String = tle.name
}
@@ -1,11 +0,0 @@
package com.rtbishop.look4sat.data
import org.osmdroid.api.IGeoPoint
import org.osmdroid.views.overlay.OverlayItem
data class SatItem(
val name: String,
val description: String,
val position: IGeoPoint,
val pass: SatPass
) : OverlayItem(name, description, position)
@@ -1,32 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.data
import com.github.amsacode.predict4java.SatPassTime
import com.github.amsacode.predict4java.TLE
import com.rtbishop.look4sat.utility.PassPredictor
data class SatPass(
val tle: TLE,
val predictor: PassPredictor,
val pass: SatPassTime,
var progress: Int = 0,
var active: Boolean = false
)
@@ -1,7 +0,0 @@
package com.rtbishop.look4sat.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "sources")
data class TleSource(@PrimaryKey var url: String = String())
@@ -1,38 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.data
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
@Entity(tableName = "transmitters")
data class Transmitter(
@PrimaryKey @SerializedName("uuid") val uuid: String,
@SerializedName("description") val description: String,
@SerializedName("alive") val isAlive: Boolean,
@SerializedName("uplink_low") val uplinkLow: Long?,
@SerializedName("uplink_high") val uplinkHigh: Long?,
@SerializedName("downlink_low") val downlinkLow: Long?,
@SerializedName("downlink_high") val downlinkHigh: Long?,
@SerializedName("mode") val mode: String?,
@SerializedName("invert") val isInverted: Boolean,
@SerializedName("norad_cat_id") val catNum: Int
)
@@ -0,0 +1,47 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework
import com.rtbishop.look4sat.domain.model.SatEntry as DomainEntry
import com.rtbishop.look4sat.domain.model.SatItem as DomainItem
import com.rtbishop.look4sat.domain.model.Transmitter as DomainTransmitter
import com.rtbishop.look4sat.framework.model.SatEntry as FrameworkEntry
import com.rtbishop.look4sat.framework.model.SatItem as FrameworkItem
import com.rtbishop.look4sat.framework.model.Transmitter as FrameworkTransmitter
fun DomainEntry.toFramework() = FrameworkEntry(this.tle, this.isSelected)
fun DomainTransmitter.toFramework() = FrameworkTransmitter(
this.uuid, this.info, this.isAlive, this.downlink,
this.uplink, this.mode, this.isInverted, this.catnum
)
fun FrameworkItem.toDomain() = DomainItem(this.catnum, this.name, this.isSelected, this.modes)
fun FrameworkTransmitter.toDomain() = DomainTransmitter(
this.uuid, this.info, this.isAlive, this.downlink,
this.uplink, this.mode, this.isInverted, this.catnum
)
fun List<DomainEntry>.toFrameworkEntries() = this.map { it.toFramework() }
fun List<DomainTransmitter>.toFramework() = this.map { it.toFramework() }
fun List<FrameworkItem>.toDomainItems() = this.map { it.toDomain() }
fun List<FrameworkTransmitter>.toDomain() = this.map { it.toDomain() }
@@ -0,0 +1,75 @@
package com.rtbishop.look4sat.framework
import android.Manifest
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.hardware.GeomagneticField
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.core.content.ContextCompat
import com.rtbishop.look4sat.domain.LocationProvider
import com.rtbishop.look4sat.domain.QthConverter
import com.rtbishop.look4sat.domain.predict.GeoPos
import com.rtbishop.look4sat.presentation.round
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LocationSource @Inject constructor(
@ApplicationContext private val context: Context,
private val preferences: SharedPreferences
) : LocationListener, LocationProvider {
private val locManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private val _updatedLocation = MutableSharedFlow<GeoPos?>()
override val updatedLocation: SharedFlow<GeoPos?> = _updatedLocation
fun getMagDeclination(stationPos: GeoPos, time: Long = System.currentTimeMillis()): Float {
val lat = stationPos.latitude.toFloat()
val lon = stationPos.longitude.toFloat()
return GeomagneticField(lat, lon, 0f, time).declination
}
fun updatePosition(latitude: Double, longitude: Double) {
if (QthConverter.isValidPosition(latitude, longitude)) {
_updatedLocation.tryEmit(GeoPos(latitude, longitude))
} else _updatedLocation.tryEmit(null)
}
fun updatePositionFromQth(qthString: String) {
val position = QthConverter.qthToPosition(qthString)
if (position != null) {
_updatedLocation.tryEmit(GeoPos(position.latitude, position.longitude))
} else _updatedLocation.tryEmit(null)
}
fun updatePositionFromGps() {
val provider = LocationManager.GPS_PROVIDER
val permission = Manifest.permission.ACCESS_FINE_LOCATION
val result = ContextCompat.checkSelfPermission(context, permission)
if (locManager.isProviderEnabled(provider) && result == PackageManager.PERMISSION_GRANTED) {
locManager.requestLocationUpdates(provider, 0L, 0f, this)
} else _updatedLocation.tryEmit(null)
}
fun updatePositionFromNetwork() {
val provider = LocationManager.NETWORK_PROVIDER
val permission = Manifest.permission.ACCESS_COARSE_LOCATION
val result = ContextCompat.checkSelfPermission(context, permission)
if (locManager.isProviderEnabled(provider) && result == PackageManager.PERMISSION_GRANTED) {
locManager.requestLocationUpdates(provider, 0L, 0f, this)
} else _updatedLocation.tryEmit(null)
}
override fun onLocationChanged(location: Location) {
locManager.removeUpdates(this)
val latitude = location.latitude.round(4)
val longitude = location.longitude.round(4)
_updatedLocation.tryEmit(GeoPos(latitude, longitude))
}
}
@@ -0,0 +1,79 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.round
@Singleton
class OrientationSource @Inject constructor(private val sensorManager: SensorManager) :
SensorEventListener {
interface OrientationListener {
fun onOrientationChanged(azimuth: Float, pitch: Float, roll: Float)
}
private val sensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
private val rotationMatrix = FloatArray(9)
private val orientationValues = FloatArray(3)
private val oneRadDegrees = 57.295779513f
private var sensorAccuracy: Int = SensorManager.SENSOR_STATUS_UNRELIABLE
private var orientationListener: OrientationListener? = null
fun startListening(listener: OrientationListener) {
if (sensor != null && orientationListener !== listener) {
orientationListener = listener
sensorManager.registerListener(this, sensor, 16000)
} else return
}
fun stopListening() {
sensorManager.unregisterListener(this)
orientationListener = null
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
sensorAccuracy = accuracy
}
override fun onSensorChanged(event: SensorEvent) {
when {
orientationListener == null -> return
sensorAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE -> return
event.sensor == sensor -> updateOrientation(event.values)
}
}
private fun updateOrientation(rotationVector: FloatArray) {
SensorManager.getRotationMatrixFromVector(rotationMatrix, rotationVector)
SensorManager.getOrientation(rotationMatrix, orientationValues)
val azimuth = orientationValues[0] * oneRadDegrees
val pitch = orientationValues[1] * oneRadDegrees
val roll = orientationValues[2] * oneRadDegrees
val magneticAzimuth = (azimuth + 360f) % 360f
val roundedAzimuth = round(magneticAzimuth * 10) / 10
val roundedPitch = round(pitch * 10) / 10
val roundedRoll = round(roll * 10) / 10
orientationListener?.onOrientationChanged(roundedAzimuth, roundedPitch, roundedRoll)
}
}
@@ -0,0 +1,155 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework
import android.content.SharedPreferences
import android.hardware.GeomagneticField
import android.location.LocationManager
import androidx.core.content.edit
import com.rtbishop.look4sat.BuildConfig
import com.rtbishop.look4sat.domain.predict.GeoPos
import com.rtbishop.look4sat.domain.QthConverter
import com.rtbishop.look4sat.presentation.round
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PreferencesSource @Inject constructor(
private val locationManager: LocationManager,
private val preferences: SharedPreferences
) {
private val keyInitialSetup = "${BuildConfig.VERSION_NAME}update"
companion object {
const val keyModes = "satModes"
const val keyCompass = "compass"
const val keyRadarSweep = "radarSweep"
const val keyTextLabels = "shouldUseTextLabels"
const val keyTimeUTC = "timeUTC"
const val keyHoursAhead = "hoursAhead"
const val keyMinElevation = "minElevation"
const val keyRotator = "isRotatorEnabled"
const val keyRotatorAddress = "rotatorAddress"
const val keyRotatorPort = "rotatorPort"
const val keyLatitude = "stationLat"
const val keyLongitude = "stationLon"
const val keyPositionGPS = "setPositionGPS"
const val keyPositionQTH = "setPositionQTH"
}
fun loadStationPosition(): GeoPos {
val defaultSP = "0.0"
val latitude = preferences.getString(keyLatitude, null) ?: defaultSP
val longitude = preferences.getString(keyLongitude, null) ?: defaultSP
return GeoPos(latitude.toDouble(), longitude.toDouble())
}
private fun saveStationPosition(pos: GeoPos) {
preferences.edit {
putString(keyLatitude, pos.latitude.toString())
putString(keyLongitude, pos.longitude.toString())
}
}
fun updatePositionFromGPS(): Boolean {
return try {
val location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
if (location == null) false
else {
val latitude = location.latitude.round(4)
val longitude = location.longitude.round(4)
val stationPosition = GeoPos(latitude, longitude)
saveStationPosition(stationPosition)
return true
}
} catch (exception: SecurityException) {
false
}
}
fun updatePositionFromQTH(qthString: String): Boolean {
val position = QthConverter.qthToPosition(qthString) ?: return false
val stationPosition = GeoPos(position.latitude, position.longitude)
saveStationPosition(stationPosition)
return true
}
fun getMagDeclination(): Float {
val stationPosition = loadStationPosition()
val lat = stationPosition.latitude.toFloat()
val lon = stationPosition.longitude.toFloat()
return GeomagneticField(lat, lon, 0f, System.currentTimeMillis()).declination
}
fun getHoursAhead(): Int {
return preferences.getInt(keyHoursAhead, 8)
}
fun getMinElevation(): Double {
return preferences.getInt(keyMinElevation, 16).toDouble()
}
fun shouldUseTextLabels(): Boolean {
return preferences.getBoolean(keyTextLabels, false)
}
fun shouldUseUTC(): Boolean {
return preferences.getBoolean(keyTimeUTC, false)
}
fun shouldUseCompass(): Boolean {
return preferences.getBoolean(keyCompass, true)
}
fun shouldShowSweep(): Boolean {
return preferences.getBoolean(keyRadarSweep, true)
}
fun isSetupDone(): Boolean {
return preferences.getBoolean(keyInitialSetup, false)
}
fun setSetupDone() {
preferences.edit { putBoolean(keyInitialSetup, true) }
}
fun saveModesSelection(modes: List<String>) {
val modesSet = modes.toSet()
preferences.edit {
putStringSet(keyModes, modesSet)
}
}
fun loadModesSelection(): List<String> {
preferences.getStringSet(keyModes, setOf())?.let { modesSet ->
return modesSet.toList().sorted()
}
return emptyList()
}
fun isRotatorEnabled(): Boolean {
return preferences.getBoolean(keyRotator, false)
}
fun getRotatorServer(): Pair<String, Int> {
val address = preferences.getString(keyRotatorAddress, null) ?: "127.0.0.1"
val port = preferences.getString(keyRotatorPort, null) ?: "4533"
return Pair(address, port.toInt())
}
}
@@ -0,0 +1,60 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.local
import androidx.room.*
import com.rtbishop.look4sat.framework.model.SatEntry
import com.rtbishop.look4sat.framework.model.SatItem
import kotlinx.coroutines.flow.Flow
@Dao
interface EntriesDao {
@Transaction
@Query("SELECT catnum, name, isSelected FROM entries ORDER BY name ASC")
fun getSatelliteItems(): Flow<List<SatItem>>
@Query("SELECT * FROM entries WHERE isSelected = 1")
suspend fun getSelectedSatellites(): List<SatEntry>
@Transaction
suspend fun updateEntries(entries: List<SatEntry>) {
val entriesSelection = getEntriesSelection()
insertEntries(entries)
restoreSelection(entriesSelection, true)
}
@Query("SELECT catnum FROM entries WHERE isSelected = 1")
suspend fun getEntriesSelection(): List<Int>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertEntries(entries: List<SatEntry>)
@Transaction
suspend fun restoreSelection(catnums: List<Int>, isSelected: Boolean) {
updateEntriesSelection(catnums, isSelected)
}
@Transaction
suspend fun updateEntriesSelection(catnums: List<Int>, isSelected: Boolean) {
catnums.forEach { catnum -> updateEntrySelection(catnum, isSelected) }
}
@Query("UPDATE entries SET isSelected = :isSelected WHERE catnum = :catnum")
suspend fun updateEntrySelection(catnum: Int, isSelected: Boolean)
}
@@ -0,0 +1,65 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.local
import com.rtbishop.look4sat.data.LocalDataSource
import com.rtbishop.look4sat.domain.model.SatEntry
import com.rtbishop.look4sat.domain.model.SatItem
import com.rtbishop.look4sat.domain.model.Transmitter
import com.rtbishop.look4sat.domain.predict.Satellite
import com.rtbishop.look4sat.framework.*
import com.rtbishop.look4sat.framework.model.Source
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class LocalSource(
private val entriesDao: EntriesDao,
private val sourcesDao: SourcesDao,
private val transmittersDao: TransmittersDao
) : LocalDataSource {
override fun getSatelliteItems(): Flow<List<SatItem>> {
return entriesDao.getSatelliteItems().map { items -> items.toDomainItems() }
}
override suspend fun getSelectedSatellites(): List<Satellite> {
return entriesDao.getSelectedSatellites().map { entry -> entry.tle.createSat() }
}
override suspend fun getSources() = sourcesDao.getSources()
override suspend fun getTransmitters(catnum: Int): List<Transmitter> {
return transmittersDao.getTransmitters(catnum).toDomain()
}
override suspend fun updateEntries(entries: List<SatEntry>) {
entriesDao.updateEntries(entries.toFrameworkEntries())
}
override suspend fun updateEntriesSelection(catnums: List<Int>, isSelected: Boolean) {
entriesDao.updateEntriesSelection(catnums, isSelected)
}
override suspend fun updateSources(sources: List<String>) {
sourcesDao.updateSources(sources.map { sourceUrl -> Source(sourceUrl) })
}
override suspend fun updateTransmitters(transmitters: List<Transmitter>) {
transmittersDao.updateTransmitters(transmitters.toFramework())
}
}
@@ -0,0 +1,68 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.local
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.rtbishop.look4sat.framework.model.Source
import com.rtbishop.look4sat.framework.model.SatEntry
import com.rtbishop.look4sat.framework.model.Transmitter
@Database(
entities = [SatEntry::class, Source::class, Transmitter::class],
version = 4,
exportSchema = true
)
abstract class SatelliteDb : RoomDatabase() {
abstract fun entriesDao(): EntriesDao
abstract fun sourcesDao(): SourcesDao
abstract fun transmittersDao(): TransmittersDao
}
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE trans_backup (uuid TEXT NOT NULL, info TEXT NOT NULL, isAlive INTEGER NOT NULL, downlink INTEGER, uplink INTEGER, mode TEXT, isInverted INTEGER NOT NULL, catNum INTEGER, PRIMARY KEY(uuid))")
database.execSQL("INSERT INTO trans_backup (uuid, info, isAlive, downlink, uplink, mode, isInverted, catNum) SELECT uuid, info, isAlive, downlink, uplink, mode, isInverted, catNum FROM transmitters")
database.execSQL("DROP TABLE transmitters")
database.execSQL("ALTER TABLE trans_backup RENAME TO transmitters")
}
}
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE sources (sourceUrl TEXT NOT NULL, PRIMARY KEY(sourceUrl))")
}
}
val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE entries_backup (isSelected INTEGER NOT NULL, name TEXT NOT NULL, epoch REAL NOT NULL, meanmo REAL NOT NULL, eccn REAL NOT NULL, incl REAL NOT NULL, raan REAL NOT NULL, argper REAL NOT NULL, meanan REAL NOT NULL, catnum INTEGER NOT NULL, bstar REAL NOT NULL, xincl REAL NOT NULL, xnodeo REAL NOT NULL, omegao REAL NOT NULL, xmo REAL NOT NULL, xno REAL NOT NULL, isDeepspace INTEGER NOT NULL, PRIMARY KEY(catnum))")
database.execSQL("INSERT INTO entries_backup (isSelected, name, epoch, meanmo, eccn, incl, raan, argper, meanan, catnum, bstar, xincl, xnodeo, omegao, xmo, xno, isDeepspace) SELECT isSelected, 'name', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, catNum, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0 FROM entries")
database.execSQL("DROP TABLE entries")
database.execSQL("ALTER TABLE entries_backup RENAME TO entries")
database.execSQL("CREATE TABLE trans_backup (uuid TEXT NOT NULL, info TEXT NOT NULL, isAlive INTEGER NOT NULL, downlink INTEGER, uplink INTEGER, mode TEXT, isInverted INTEGER NOT NULL, catnum INTEGER, PRIMARY KEY(uuid))")
database.execSQL("INSERT INTO trans_backup (uuid, info, isAlive, downlink, uplink, mode, isInverted, catnum) SELECT uuid, info, isAlive, downlink, uplink, mode, isInverted, catNum FROM transmitters")
database.execSQL("DROP TABLE transmitters")
database.execSQL("ALTER TABLE trans_backup RENAME TO transmitters")
}
}
@@ -0,0 +1,40 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.local
import androidx.room.*
import com.rtbishop.look4sat.framework.model.Source
@Dao
interface SourcesDao {
@Query("SELECT sourceUrl FROM sources")
suspend fun getSources(): List<String>
@Transaction
suspend fun updateSources(sources: List<Source>) {
deleteSources()
insertSources(sources)
}
@Query("DELETE from sources")
suspend fun deleteSources()
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSources(sources: List<Source>)
}
@@ -0,0 +1,31 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.local
import androidx.room.*
import com.rtbishop.look4sat.framework.model.Transmitter
@Dao
interface TransmittersDao {
@Query("SELECT * FROM transmitters WHERE catnum = :catnum")
suspend fun getTransmitters(catnum: Int): List<Transmitter>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateTransmitters(transmitters: List<Transmitter>)
}
@@ -0,0 +1,29 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.model
import androidx.room.Embedded
import androidx.room.Entity
import com.rtbishop.look4sat.domain.predict.TLE
@Entity(tableName = "entries", primaryKeys = ["catnum"])
data class SatEntry(
@Embedded
val tle: TLE,
var isSelected: Boolean = false
)
@@ -0,0 +1,33 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.model
import androidx.room.Relation
data class SatItem(
val catnum: Int,
val name: String,
var isSelected: Boolean,
@Relation(
parentColumn = "catnum",
entity = Transmitter::class,
entityColumn = "catnum",
projection = ["mode"]
)
val modes: List<String>
)
@@ -0,0 +1,24 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "sources")
data class Source(@PrimaryKey var sourceUrl: String = String())
@@ -0,0 +1,33 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.framework.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "transmitters")
data class Transmitter(
@PrimaryKey val uuid: String,
val info: String,
val isAlive: Boolean,
var downlink: Long?,
var uplink: Long?,
val mode: String?,
val isInverted: Boolean,
val catnum: Int?
)
@@ -0,0 +1,19 @@
package com.rtbishop.look4sat.framework.remote
import com.rtbishop.look4sat.data.RemoteDataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.net.URL
class RemoteSource(private val ioDispatcher: CoroutineDispatcher) : RemoteDataSource {
@Suppress("BlockingMethodInNonBlockingContext")
override suspend fun fetchFileStream(url: String): InputStream? {
return try {
withContext(ioDispatcher) { URL(url).openStream() }
} catch (e: Exception) {
null
}
}
}
@@ -0,0 +1,60 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.injection
import android.content.ContentResolver
import android.content.Context
import android.content.SharedPreferences
import android.hardware.SensorManager
import android.location.LocationManager
import androidx.preference.PreferenceManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideContentResolver(@ApplicationContext context: Context): ContentResolver {
return context.contentResolver
}
@Provides
@Singleton
fun provideLocationManager(@ApplicationContext context: Context): LocationManager {
return context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
@Provides
@Singleton
fun provideSensorManager(@ApplicationContext context: Context): SensorManager {
return context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
@Provides
@Singleton
fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(context)
}
}
@@ -0,0 +1,67 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.injection
import android.content.Context
import androidx.room.Room
import com.rtbishop.look4sat.data.DefaultRepository
import com.rtbishop.look4sat.domain.DataParser
import com.rtbishop.look4sat.domain.DataRepository
import com.rtbishop.look4sat.domain.DataReporter
import com.rtbishop.look4sat.domain.predict.Predictor
import com.rtbishop.look4sat.framework.local.*
import com.rtbishop.look4sat.framework.remote.RemoteSource
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object CoreModule {
@Provides
@Singleton
fun provideSatelliteRepo(
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher,
@DefaultDispatcher defaultDispatcher: CoroutineDispatcher
): DataRepository {
val dataParser = DataParser(defaultDispatcher)
val db = Room.databaseBuilder(context, SatelliteDb::class.java, "SatelliteDb")
.addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4).build()
val localSource = LocalSource(db.entriesDao(), db.sourcesDao(), db.transmittersDao())
val remoteSource = RemoteSource(ioDispatcher)
return DefaultRepository(dataParser, localSource, remoteSource)
}
@Provides
@Singleton
fun providePredictor(@DefaultDispatcher dispatcher: CoroutineDispatcher): Predictor {
return Predictor(dispatcher)
}
@Provides
@Singleton
fun provideDataReporter(@IoDispatcher dispatcher: CoroutineDispatcher): DataReporter {
return DataReporter(dispatcher)
}
}
@@ -0,0 +1,55 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.injection
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import javax.inject.Qualifier
@Module
@InstallIn(SingletonComponent::class)
object KotlinModule {
@Provides
@DefaultDispatcher
fun provideDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
@Provides
@IoDispatcher
fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
@Provides
@MainDispatcher
fun provideMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
}
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class DefaultDispatcher
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IoDispatcher
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class MainDispatcher
@@ -1,53 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.network
import android.util.Log
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.InputStream
import javax.inject.Inject
class RemoteDataSource @Inject constructor(
private val api: TransmittersApi,
private val client: OkHttpClient
) : RemoteSource {
override suspend fun fetchTleStreams(urlList: List<TleSource>): List<InputStream> {
val streams = mutableListOf<InputStream>()
withContext(Dispatchers.IO) {
urlList.withIndex().forEach {
val request = Request.Builder().url(it.value.url).build()
val stream = client.newCall(request).execute().body?.byteStream()
stream?.let { inputStream -> streams.add(inputStream) }
}
}
Log.d("myTag", urlList.toString())
return streams
}
override suspend fun fetchTransmitters(): List<Transmitter> {
return api.fetchTransmitters()
}
}
@@ -1,12 +0,0 @@
package com.rtbishop.look4sat.network
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
import java.io.InputStream
interface RemoteSource {
suspend fun fetchTleStreams(urlList: List<TleSource>): List<InputStream>
suspend fun fetchTransmitters(): List<Transmitter>
}
@@ -1,29 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.network
import com.rtbishop.look4sat.data.Transmitter
import retrofit2.http.GET
interface TransmittersApi {
@GET("transmitters/")
suspend fun fetchTransmitters(): List<Transmitter>
}
@@ -1,84 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.persistence
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
import com.rtbishop.look4sat.persistence.dao.EntriesDao
import com.rtbishop.look4sat.persistence.dao.SourcesDao
import com.rtbishop.look4sat.persistence.dao.TransmittersDao
import javax.inject.Inject
class LocalDataSource @Inject constructor(
private val entriesDao: EntriesDao,
private val transmittersDao: TransmittersDao,
private val sourcesDao: SourcesDao
) : LocalSource {
override suspend fun insertEntries(entries: List<SatEntry>) {
entriesDao.insertEntries(entries)
}
override suspend fun getAllEntries(): List<SatEntry> {
return entriesDao.getAllEntries()
}
override suspend fun getSelectedEntries(): List<SatEntry> {
return entriesDao.getSelectedEntries()
}
override suspend fun updateEntriesSelection(catNumList: List<Int>) {
entriesDao.clearEntriesSelection()
catNumList.forEach { entriesDao.updateEntrySelection(it) }
}
override suspend fun clearEntries() {
entriesDao.clearEntries()
}
////////////////////////////////////////////////////////////////////////////////////////////////
override suspend fun insertTransmitters(transmitters: List<Transmitter>) {
transmittersDao.insertTransmitters(transmitters)
}
override suspend fun getTransmittersByCatNum(catNum: Int): List<Transmitter> {
return transmittersDao.getTransmittersByCatNum(catNum)
}
override suspend fun clearTransmitters() {
transmittersDao.clearTransmitters()
}
////////////////////////////////////////////////////////////////////////////////////////////////
override suspend fun insertSources(sources: List<TleSource>) {
sourcesDao.insertSources(sources)
}
override suspend fun getSources(): List<TleSource> {
return sourcesDao.getSources()
}
override suspend fun clearSources() {
sourcesDao.clearSources()
}
}
@@ -1,34 +0,0 @@
package com.rtbishop.look4sat.persistence
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
interface LocalSource {
suspend fun insertEntries(entries: List<SatEntry>)
suspend fun getAllEntries(): List<SatEntry>
suspend fun getSelectedEntries(): List<SatEntry>
suspend fun updateEntriesSelection(catNumList: List<Int>)
suspend fun clearEntries()
////////////////////////////////////////////////////////////////////////////////////////////////
suspend fun insertTransmitters(transmitters: List<Transmitter>)
suspend fun getTransmittersByCatNum(catNum: Int): List<Transmitter>
suspend fun clearTransmitters()
////////////////////////////////////////////////////////////////////////////////////////////////
suspend fun insertSources(sources: List<TleSource>)
suspend fun getSources(): List<TleSource>
suspend fun clearSources()
}
@@ -1,46 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.persistence
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
import com.rtbishop.look4sat.persistence.dao.EntriesDao
import com.rtbishop.look4sat.persistence.dao.SourcesDao
import com.rtbishop.look4sat.persistence.dao.TransmittersDao
import com.rtbishop.look4sat.utility.Converters
@Database(
entities = [Transmitter::class, SatEntry::class, TleSource::class],
version = 1,
exportSchema = false
)
@TypeConverters(Converters::class)
abstract class SatelliteDb : RoomDatabase() {
abstract fun entriesDao(): EntriesDao
abstract fun transmittersDao(): TransmittersDao
abstract fun sourcesDao(): SourcesDao
}
@@ -1,48 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.persistence.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.rtbishop.look4sat.data.SatEntry
@Dao
interface EntriesDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertEntries(entries: List<SatEntry>)
@Query("SELECT * FROM entries ORDER BY name ASC")
suspend fun getAllEntries(): List<SatEntry>
@Query("SELECT * FROM entries WHERE isSelected = 1 ORDER BY name ASC")
suspend fun getSelectedEntries(): List<SatEntry>
@Query("UPDATE entries SET isSelected = 1 WHERE catNum == :catNum")
suspend fun updateEntrySelection(catNum: Int)
@Query("UPDATE entries SET isSelected = 0")
suspend fun clearEntriesSelection()
@Query("DELETE FROM entries")
suspend fun clearEntries()
}
@@ -1,20 +0,0 @@
package com.rtbishop.look4sat.persistence.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.rtbishop.look4sat.data.TleSource
@Dao
interface SourcesDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSources(sources: List<TleSource>)
@Query("SELECT * FROM sources")
suspend fun getSources(): List<TleSource>
@Query("DELETE FROM sources")
suspend fun clearSources()
}
@@ -1,20 +0,0 @@
package com.rtbishop.look4sat.persistence.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.rtbishop.look4sat.data.Transmitter
@Dao
interface TransmittersDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertTransmitters(transmitters: List<Transmitter>)
@Query("SELECT * FROM transmitters WHERE isAlive = 1 and catNum = :catNum")
suspend fun getTransmittersByCatNum(catNum: Int): List<Transmitter>
@Query("DELETE FROM transmitters")
suspend fun clearTransmitters()
}
@@ -0,0 +1,108 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.Navigator
import androidx.navigation.fragment.findNavController
import java.security.MessageDigest
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
fun Context.toast(text: String, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).apply { show() }
}
fun SharedPreferences.getDouble(key: String, default: Double): Double {
return Double.fromBits(getLong(key, default.toRawBits()))
}
fun SharedPreferences.Editor.putDouble(key: String, double: Double) {
putLong(key, double.toRawBits())
}
fun NavController.navigateSafe(
@IdRes resId: Int,
args: Bundle? = null,
options: NavOptions? = null,
extras: Navigator.Extras? = null
) {
val action = currentDestination?.getAction(resId) ?: graph.getAction(resId)
if (action != null && currentDestination?.id != action.destinationId) {
navigate(resId, args, options, extras)
}
}
fun <T> Fragment.getNavResult(@IdRes id: Int, key: String, onResult: (result: T) -> Unit) {
val backStackEntry = findNavController().getBackStackEntry(id)
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME && backStackEntry.savedStateHandle.contains(key)) {
backStackEntry.savedStateHandle.get<T>(key)?.let(onResult)
backStackEntry.savedStateHandle.remove<T>(key)
}
}
backStackEntry.lifecycle.addObserver(observer)
viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_DESTROY) backStackEntry.lifecycle.removeObserver(observer)
})
}
fun <T> Fragment.setNavResult(key: String, value: T) {
findNavController().previousBackStackEntry?.savedStateHandle?.set(key, value)
}
fun Long.toTimerString(): String {
val format = "%02d:%02d:%02d"
val hours = TimeUnit.MILLISECONDS.toHours(this)
val minutes = TimeUnit.MILLISECONDS.toMinutes(this) % 60
val seconds = TimeUnit.MILLISECONDS.toSeconds(this) % 60
return String.format(format, hours, minutes, seconds)
}
fun Double.round(decimals: Int): Double {
var multiplier = 1.0
repeat(decimals) { multiplier *= 10 }
return kotlin.math.round(this * multiplier) / multiplier
}
fun String.getHash(type: String = "SHA-256"): String {
val hexChars = "0123456789ABCDEF"
val bytes = MessageDigest.getInstance(type).digest(this.toByteArray())
val result = StringBuilder(bytes.size * 2)
bytes.forEach {
val i = it.toInt()
result.append(hexChars[i shr 4 and 0x0f])
result.append(hexChars[i and 0x0f])
}
return result.toString()
}
fun String.isEmailValid(): Boolean {
val expression = "^[\\w.-]+@([\\w\\-]+\\.)+[A-Z]{2,8}$"
val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
return pattern.matcher(this).matches()
}
@@ -0,0 +1,44 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation
import android.graphics.Canvas
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
class ItemDivider(private val resId: Int) : RecyclerView.ItemDecoration() {
override fun onDrawOver(canvas: Canvas, parent: RecyclerView) {
ContextCompat.getDrawable(parent.context, resId)?.let { drawable ->
val leftPos = parent.paddingLeft
val rightPos = parent.width - parent.paddingRight
parent.adapter?.itemCount?.let { childCount ->
for (i in 0 until childCount) {
if (i == (childCount - 1)) continue
parent.getChildAt(i)?.let { view ->
val params = view.layoutParams as RecyclerView.LayoutParams
val topPos = view.bottom + params.bottomMargin
val bottomPos = topPos + drawable.intrinsicHeight
drawable.setBounds(leftPos, topPos, rightPos, bottomPos)
drawable.draw(canvas)
}
}
}
}
}
}
@@ -0,0 +1,44 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class Look4SatActivity : AppCompatActivity() {
@SuppressLint("SourceLockedOrientationActivity")
override fun onCreate(savedInstanceState: Bundle?) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
super.onCreate(savedInstanceState)
installSplashScreen()
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHost = supportFragmentManager.findFragmentById(R.id.main_nav_host) as NavHostFragment
binding.mainNavBottom.setupWithNavController(navHost.navController)
}
}
@@ -0,0 +1,32 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation
import android.app.Application
import com.rtbishop.look4sat.BuildConfig
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
@HiltAndroidApp
class Look4SatApplication : Application() {
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree())
}
}
@@ -0,0 +1,78 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.entriesScreen
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.domain.model.SatItem
import com.rtbishop.look4sat.databinding.ItemEntryBinding
class EntriesAdapter(private val clickListener: EntriesClickListener) :
RecyclerView.Adapter<EntriesAdapter.SatItemHolder>() {
private val diffCallback = object : DiffUtil.ItemCallback<SatItem>() {
override fun areItemsTheSame(oldItem: SatItem, newItem: SatItem): Boolean {
return oldItem.catnum == newItem.catnum
}
override fun areContentsTheSame(oldItem: SatItem, newItem: SatItem): Boolean {
return oldItem.isSelected == newItem.isSelected
}
}
private val differ = AsyncListDiffer(this, diffCallback)
fun submitList(items: List<SatItem>) {
differ.submitList(items)
}
override fun getItemCount(): Int = differ.currentList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SatItemHolder {
return SatItemHolder.from(parent)
}
override fun onBindViewHolder(holder: SatItemHolder, position: Int) {
holder.bind(differ.currentList[position], clickListener)
}
class SatItemHolder private constructor(private val binding: ItemEntryBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: SatItem, listener: EntriesClickListener) {
binding.entryCheckbox.text = item.name
binding.entryCheckbox.isChecked = item.isSelected
itemView.setOnClickListener {
listener.updateSelection(listOf(item.catnum), item.isSelected.not())
}
}
companion object {
fun from(parent: ViewGroup): SatItemHolder {
val inflater = LayoutInflater.from(parent.context)
return SatItemHolder(ItemEntryBinding.inflate(inflater, parent, false))
}
}
}
interface EntriesClickListener {
fun updateSelection(catNums: List<Int>, isSelected: Boolean)
}
}
@@ -0,0 +1,135 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.entriesScreen
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.google.android.material.snackbar.Snackbar
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.FragmentEntriesBinding
import com.rtbishop.look4sat.domain.model.SatItem
import com.rtbishop.look4sat.domain.model.DataState
import com.rtbishop.look4sat.presentation.ItemDivider
import com.rtbishop.look4sat.presentation.getNavResult
import com.rtbishop.look4sat.presentation.navigateSafe
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class EntriesFragment : Fragment(R.layout.fragment_entries) {
private val viewModel: EntriesViewModel by viewModels()
private val contentContract = ActivityResultContracts.GetContent()
private val filePicker = registerForActivityResult(contentContract) { uri ->
uri?.let { viewModel.updateDataFromFile(uri) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupComponents(view)
}
private fun setupComponents(view: View) {
val entriesAdapter = EntriesAdapter(viewModel)
val binding = FragmentEntriesBinding.bind(view).apply {
entriesRecycler.apply {
setHasFixedSize(true)
adapter = entriesAdapter
layoutManager = GridLayoutManager(requireContext(), 2)
(itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
addItemDecoration(ItemDivider(R.drawable.rec_divider_light))
}
entriesImportWeb.setOnClickListener {
findNavController().navigateSafe(R.id.action_entries_to_sources)
}
entriesImportFile.setOnClickListener { filePicker.launch("*/*") }
entriesSelectMode.setOnClickListener { showModesDialog() }
entriesSelectAll.setOnClickListener { viewModel.selectCurrentItems() }
entriesSearchBar.setOnQueryTextListener(viewModel)
entriesSearchBar.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
}
viewModel.satData.observe(viewLifecycleOwner, { satData ->
handleSatData(satData, binding, entriesAdapter)
})
getNavResult<List<String>>(R.id.nav_entries, "sources") { sources ->
viewModel.updateDataFromWeb(sources)
}
}
private fun handleSatData(
dataState: DataState<List<SatItem>>,
binding: FragmentEntriesBinding,
entriesAdapter: EntriesAdapter
) {
when (dataState) {
is DataState.Success -> {
entriesAdapter.submitList(dataState.data)
binding.entriesProgress.visibility = View.INVISIBLE
binding.entriesRecycler.visibility = View.VISIBLE
}
is DataState.Loading -> {
binding.entriesProgress.visibility = View.VISIBLE
binding.entriesRecycler.visibility = View.INVISIBLE
}
is DataState.Error -> {
binding.entriesProgress.visibility = View.INVISIBLE
binding.entriesRecycler.visibility = View.VISIBLE
val message = getString(R.string.entries_update_error)
Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT).show()
}
else -> {
}
}
}
private fun showModesDialog() {
val modes = arrayOf(
"AFSK", "AFSK S-Net", "AFSK SALSAT", "AHRPT", "AM", "APT", "BPSK", "BPSK PMT-A3",
"CERTO", "CW", "DQPSK", "DSTAR", "DUV", "FFSK", "FM", "FMN", "FSK", "FSK AX.100 Mode 5",
"FSK AX.100 Mode 6", "FSK AX.25 G3RUH", "GFSK", "GFSK Rktr", "GMSK", "HRPT", "LoRa",
"LRPT", "LSB", "MFSK", "MSK", "MSK AX.100 Mode 5", "MSK AX.100 Mode 6", "OFDM", "OQPSK",
"PSK", "PSK31", "PSK63", "QPSK", "QPSK31", "QPSK63", "SSTV", "USB", "WSJT"
)
val savedModes = BooleanArray(modes.size)
val selectedModes = viewModel.loadSelectedModes().toMutableList()
selectedModes.forEach { savedModes[modes.indexOf(it)] = true }
AlertDialog.Builder(requireContext()).apply {
setTitle(context.getString(R.string.modes_title))
setMultiChoiceItems(modes, savedModes) { _, which, isChecked ->
when {
isChecked -> selectedModes.add(modes[which])
selectedModes.contains(modes[which]) -> selectedModes.remove(modes[which])
}
}
setPositiveButton(context.getString(android.R.string.ok)) { _, _ ->
viewModel.saveSelectedModes(selectedModes)
}
setNeutralButton(context.getString(android.R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
create().show()
}
}
}
@@ -0,0 +1,125 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.entriesScreen
import android.content.ContentResolver
import android.net.Uri
import android.widget.SearchView
import androidx.lifecycle.*
import com.rtbishop.look4sat.domain.model.SatItem
import com.rtbishop.look4sat.domain.model.DataState
import com.rtbishop.look4sat.domain.DataRepository
import com.rtbishop.look4sat.framework.PreferencesSource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.*
import javax.inject.Inject
@HiltViewModel
class EntriesViewModel @Inject constructor(
private val preferences: PreferencesSource,
private val resolver: ContentResolver,
private val dataRepository: DataRepository
) : ViewModel(), SearchView.OnQueryTextListener, EntriesAdapter.EntriesClickListener {
private val coroutineHandler = CoroutineExceptionHandler { _, throwable ->
Timber.d(throwable)
_satData.value = DataState.Error(throwable)
}
private val transModes = MutableLiveData(preferences.loadModesSelection())
private val currentQuery = MutableLiveData(String())
private val itemsWithModes = transModes.switchMap { modes ->
liveData { dataRepository.getSatelliteItems().collect { emit(filterByModes(it, modes)) } }
}
private val itemsWithQuery = currentQuery.switchMap { query ->
itemsWithModes.map { items -> DataState.Success(filterByQuery(items, query)) }
}
private val _satData = MediatorLiveData<DataState<List<SatItem>>>().apply {
addSource(itemsWithQuery) { value -> this.value = value }
}
private var shouldSelectAll = true
val satData: LiveData<DataState<List<SatItem>>> = _satData
fun updateDataFromFile(uri: Uri) {
viewModelScope.launch(coroutineHandler) {
_satData.value = DataState.Loading
runCatching {
resolver.openInputStream(uri)?.use { stream ->
dataRepository.updateDataFromFile(stream)
}
}.onFailure { _satData.value = DataState.Error(it) }
}
}
fun updateDataFromWeb(sources: List<String>) {
viewModelScope.launch(coroutineHandler) {
_satData.value = DataState.Loading
dataRepository.updateDataFromWeb(sources)
}
}
fun selectCurrentItems() {
val currentValue = _satData.value
if (currentValue is DataState.Success) {
updateSelection(currentValue.data.map { it.catnum }, shouldSelectAll)
shouldSelectAll = shouldSelectAll.not()
}
}
fun loadSelectedModes(): List<String> {
return preferences.loadModesSelection()
}
fun saveSelectedModes(modes: List<String>) {
transModes.value = modes
preferences.saveModesSelection(modes)
}
override fun onQueryTextSubmit(query: String): Boolean {
return true
}
override fun onQueryTextChange(newText: String): Boolean {
currentQuery.value = newText
return true
}
override fun updateSelection(catNums: List<Int>, isSelected: Boolean) {
viewModelScope.launch { dataRepository.updateSelection(catNums, isSelected) }
}
private fun filterByModes(items: List<SatItem>, modes: List<String>): List<SatItem> {
if (modes.isEmpty()) return items
return items.filter { item -> item.modes.any { mode -> mode in modes } }
}
private fun filterByQuery(items: List<SatItem>, query: String): List<SatItem> {
if (query.isBlank()) return items
return try {
items.filter { it.catnum == query.toInt() }
} catch (e: Exception) {
items.filter { item ->
val itemName = item.name.lowercase(Locale.getDefault())
itemName.contains(query.lowercase(Locale.getDefault()))
}
}
}
}
@@ -0,0 +1,55 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.infoScreen
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import androidx.fragment.app.Fragment
import com.rtbishop.look4sat.BuildConfig
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.FragmentInfoBinding
class InfoFragment : Fragment(R.layout.fragment_info) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
FragmentInfoBinding.bind(view).apply {
infoVersion.text =
String.format(getString(R.string.info_version), BuildConfig.VERSION_NAME)
infoBtnGithub.setOnClickListener {
gotoUrl("https://github.com/rt-bishop/Look4Sat/")
}
infoBtnFdroid.setOnClickListener {
gotoUrl("https://f-droid.org/en/packages/com.rtbishop.look4sat/")
}
infoBtnDonate.setOnClickListener {
gotoUrl("https://www.buymeacoffee.com/rtbishop")
}
val moveMethod = LinkMovementMethod.getInstance()
infoThanks.movementMethod = moveMethod
infoWarranty.movementMethod = moveMethod
}
}
private fun gotoUrl(url: String) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
}
@@ -0,0 +1,32 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.mapScreen
import com.rtbishop.look4sat.domain.predict.GeoPos
import com.rtbishop.look4sat.domain.predict.Satellite
data class MapData(
val pass: Satellite,
val catNum: Int,
val name: String,
val range: Double,
val altitude: Double,
val velocity: Double,
val qthLoc: String,
val osmPos: GeoPos
)
@@ -0,0 +1,205 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.mapScreen
import android.content.SharedPreferences
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.FragmentMapBinding
import com.rtbishop.look4sat.domain.predict.GeoPos
import com.rtbishop.look4sat.domain.predict.Satellite
import dagger.hilt.android.AndroidEntryPoint
import org.osmdroid.config.Configuration
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.*
import timber.log.Timber
import java.util.*
import javax.inject.Inject
@AndroidEntryPoint
class MapFragment : Fragment(R.layout.fragment_map) {
@Inject
lateinit var sharedPreferences: SharedPreferences
private val viewModel: MapViewModel by viewModels()
private val minLat = MapView.getTileSystem().minLatitude
private val maxLat = MapView.getTileSystem().maxLatitude
private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
strokeWidth = 2f
style = Paint.Style.STROKE
color = Color.RED
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
}
private val footprintPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL_AND_STROKE
color = Color.parseColor("#26FFE082")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Configuration.getInstance().load(requireContext(), sharedPreferences)
val binding = FragmentMapBinding.bind(view).apply {
mapView.apply {
setMultiTouchControls(true)
setTileSource(TileSourceFactory.WIKIMEDIA)
minZoomLevel = getMinZoom(resources.displayMetrics.heightPixels) + 0.25
maxZoomLevel = 5.75
controller.setZoom(minZoomLevel + 0.25)
zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
overlayManager.tilesOverlay.loadingBackgroundColor = Color.TRANSPARENT
overlayManager.tilesOverlay.loadingLineColor = Color.TRANSPARENT
overlayManager.tilesOverlay.setColorFilter(getColorFilter())
setScrollableAreaLimitLatitude(maxLat, minLat, 0)
// add overlays: 0 - GSP, 1 - SatTrack, 2 - SatFootprint, 3 - SatIcons
overlays.addAll(Array(4) { FolderOverlay() })
}
}
binding.mapBtnPrev.setOnClickListener { viewModel.scrollSelection(true) }
binding.mapBtnNext.setOnClickListener { viewModel.scrollSelection(false) }
setupObservers(binding)
}
private fun setupObservers(binding: FragmentMapBinding) {
viewModel.selectDefaultSatellite(arguments?.getInt("catNum"))
viewModel.stationPosLiveData.observe(viewLifecycleOwner, { renderStationPos(it, binding) })
viewModel.satPositions.observe(viewLifecycleOwner, { renderSatPositions(it, binding) })
viewModel.satTrack.observe(viewLifecycleOwner, { renderSatTrack(it, binding) })
viewModel.satFootprint.observe(viewLifecycleOwner, { renderSatFootprint(it, binding) })
viewModel.mapData.observe(viewLifecycleOwner, { renderSatData(it, binding) })
}
private fun renderStationPos(stationPos: GeoPos, binding: FragmentMapBinding) {
binding.apply {
Marker(mapView).apply {
setInfoWindow(null)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = ContextCompat.getDrawable(requireContext(), R.drawable.ic_map_pos)
position = GeoPoint(stationPos.latitude, stationPos.longitude)
mapView.overlays[0] = this
mapView.invalidate()
}
}
}
private fun renderSatPositions(posMap: Map<Satellite, GeoPos>, binding: FragmentMapBinding) {
binding.apply {
val markers = FolderOverlay()
posMap.entries.forEach {
Marker(mapView).apply {
setInfoWindow(null)
textLabelFontSize = 24
textLabelBackgroundColor = Color.TRANSPARENT
textLabelForegroundColor =
ContextCompat.getColor(requireContext(), R.color.themeLight)
setTextIcon(it.key.params.name)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
try {
position = GeoPoint(it.value.latitude, it.value.longitude)
} catch (exception: IllegalArgumentException) {
Timber.d(exception)
}
setOnMarkerClickListener { _, _ ->
viewModel.selectSatellite(it.key)
return@setOnMarkerClickListener true
}
markers.add(this)
}
}
mapView.overlays[3] = markers
mapView.invalidate()
}
}
private fun renderSatTrack(satTrack: List<List<GeoPos>>, binding: FragmentMapBinding) {
val trackOverlay = FolderOverlay()
satTrack.forEach { track ->
val trackPoints = track.map { GeoPoint(it.latitude, it.longitude) }
Polyline().apply {
try {
setPoints(trackPoints)
outlinePaint.set(trackPaint)
trackOverlay.add(this)
} catch (exception: IllegalArgumentException) {
Timber.d(exception)
}
}
}
binding.mapView.overlays[1] = trackOverlay
}
private fun renderSatFootprint(satFootprint: List<GeoPos>, binding: FragmentMapBinding) {
val footprintPoints = satFootprint.map { GeoPoint(it.latitude, it.longitude) }
val footprintOverlay = Polygon().apply {
fillPaint.set(footprintPaint)
outlinePaint.set(footprintPaint)
try {
this.points = footprintPoints
} catch (exception: IllegalArgumentException) {
Timber.d(exception)
}
}
binding.mapView.overlays[2] = footprintOverlay
}
private fun renderSatData(mapData: MapData, binding: FragmentMapBinding) {
binding.apply {
mapDataName.text =
String.format(getString(R.string.pat_osm_idName), mapData.catNum, mapData.name)
mapDataQth.text = String.format(getString(R.string.map_qth), mapData.qthLoc)
mapDataAlt.text = String.format(getString(R.string.pat_altitude), mapData.altitude)
mapDataDst.text = String.format(getString(R.string.pat_distance), mapData.range)
mapDataVel.text = String.format(getString(R.string.pat_osm_vel), mapData.velocity)
mapDataLat.text =
String.format(getString(R.string.pat_osm_lat), mapData.osmPos.latitude)
mapDataLon.text =
String.format(getString(R.string.pat_osm_lon), mapData.osmPos.longitude)
}
binding.mapView.invalidate()
}
private fun getColorFilter(): ColorMatrixColorFilter {
val grayScaleMatrix = ColorMatrix().apply { setSaturation(0f) }
val negativeMatrix = ColorMatrix(
floatArrayOf(
-1f, 0f, 0f, 0f, 255f,
0f, -1f, 0f, 0f, 255f,
0f, 0f, -1f, 0f, 255f,
0f, 0f, 0f, 1f, 0f
)
)
negativeMatrix.preConcat(grayScaleMatrix)
return ColorMatrixColorFilter(negativeMatrix)
}
private fun getMinZoom(screenHeight: Int): Double {
return MapView.getTileSystem().getLatitudeZoom(maxLat, minLat, screenHeight)
}
}
@@ -0,0 +1,191 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.mapScreen
import androidx.lifecycle.*
import com.rtbishop.look4sat.domain.predict.Predictor
import com.rtbishop.look4sat.domain.DataRepository
import com.rtbishop.look4sat.framework.PreferencesSource
import com.rtbishop.look4sat.domain.predict.GeoPos
import com.rtbishop.look4sat.domain.QthConverter
import com.rtbishop.look4sat.domain.predict.Satellite
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import java.util.*
import javax.inject.Inject
import kotlin.math.max
import kotlin.math.min
@HiltViewModel
class MapViewModel @Inject constructor(
private val dataRepository: DataRepository,
private val predictor: Predictor,
private val preferences: PreferencesSource,
) : ViewModel() {
private val stationPos = preferences.loadStationPosition()
private var dataUpdateJob: Job? = null
private var allSatList = listOf<Satellite>()
private lateinit var selectedSat: Satellite
val stationPosLiveData = liveData {
val osmLat = clipLat(stationPos.latitude)
val osmLon = clipLon(stationPos.longitude)
emit(GeoPos(osmLat, osmLon))
}
private val _satTrack = MutableLiveData<List<List<GeoPos>>>()
val satTrack: LiveData<List<List<GeoPos>>> = _satTrack
private val _satFootprint = MutableLiveData<List<GeoPos>>()
val satFootprint: LiveData<List<GeoPos>> = _satFootprint
private val _satData = MutableLiveData<MapData>()
val mapData: LiveData<MapData> = this._satData
private val _satPositions = MutableLiveData<Map<Satellite, GeoPos>>()
val satPositions: LiveData<Map<Satellite, GeoPos>> = _satPositions
fun shouldUseTextLabels(): Boolean {
return preferences.shouldUseTextLabels()
}
fun scrollSelection(decrement: Boolean) {
if (allSatList.isNotEmpty()) {
val index = allSatList.indexOf(selectedSat)
if (decrement) {
if (index > 0) selectSatellite(allSatList[index - 1])
else selectSatellite(allSatList[allSatList.size - 1])
} else {
if (index < allSatList.size - 1) selectSatellite(allSatList[index + 1])
else selectSatellite(allSatList[0])
}
}
}
fun selectDefaultSatellite(catnum: Int?) {
viewModelScope.launch {
dataRepository.getSelectedSatellites().also { satellites ->
if (satellites.isNotEmpty()) {
allSatList = satellites
if (catnum == null) {
selectSatellite(satellites.first())
} else {
satellites.find { it.params.catnum == catnum }?.let { selectSatellite(it) }
}
}
}
}
}
fun selectSatellite(satellite: Satellite, updateFreq: Long = 2000) {
selectedSat = satellite
viewModelScope.launch {
dataUpdateJob?.cancelAndJoin()
dataUpdateJob = launch {
val dateNow = Date()
getSatTrack(selectedSat, stationPos, dateNow)
while (isActive) {
dateNow.time = System.currentTimeMillis()
getPositions(allSatList, stationPos, dateNow)
getSatFootprint(selectedSat, stationPos, dateNow)
getSatData(selectedSat, stationPos, dateNow)
delay(updateFreq)
}
}
}
}
private suspend fun getSatTrack(satellite: Satellite, pos: GeoPos, date: Date) {
val satTracks = mutableListOf<List<GeoPos>>()
val currentTrack = mutableListOf<GeoPos>()
val endDate = Date(date.time + (satellite.orbitalPeriod * 2.4 * 60000L).toLong())
var oldLongitude = 0.0
predictor.getSatTrack(satellite, pos, date.time, endDate.time).forEach { satPos ->
val osmLat = clipLat(Math.toDegrees(satPos.latitude))
val osmLon = clipLon(Math.toDegrees(satPos.longitude))
val currentPosition = GeoPos(osmLat, osmLon)
if (oldLongitude < -170.0 && currentPosition.longitude > 170.0) {
// adding left terminal position
currentTrack.add(GeoPos(osmLat, -180.0))
val finishedTrack = mutableListOf<GeoPos>().apply { addAll(currentTrack) }
satTracks.add(finishedTrack)
currentTrack.clear()
} else if (oldLongitude > 170.0 && currentPosition.longitude < -170.0) {
// adding right terminal position
currentTrack.add(GeoPos(osmLat, 180.0))
val finishedTrack = mutableListOf<GeoPos>().apply { addAll(currentTrack) }
satTracks.add(finishedTrack)
currentTrack.clear()
}
oldLongitude = currentPosition.longitude
currentTrack.add(currentPosition)
}
satTracks.add(currentTrack)
_satTrack.postValue(satTracks)
}
private suspend fun getPositions(satellites: List<Satellite>, pos: GeoPos, date: Date) {
val positions = mutableMapOf<Satellite, GeoPos>()
satellites.forEach { satellite ->
val satPos = predictor.getSatPos(satellite, pos, date.time)
val osmLat = clipLat(Math.toDegrees(satPos.latitude))
val osmLon = clipLon(Math.toDegrees(satPos.longitude))
positions[satellite] = GeoPos(osmLat, osmLon)
}
_satPositions.postValue(positions)
}
private suspend fun getSatFootprint(satellite: Satellite, pos: GeoPos, date: Date) {
val satPos = predictor.getSatPos(satellite, pos, date.time)
val satFootprint = satPos.getRangeCircle().map { rangePos ->
val osmLat = clipLat(rangePos.latitude)
val osmLon = clipLon(rangePos.longitude)
GeoPos(osmLat, osmLon)
}
_satFootprint.postValue(satFootprint)
}
private suspend fun getSatData(satellite: Satellite, pos: GeoPos, date: Date) {
val satPos = predictor.getSatPos(satellite, pos, date.time)
val osmLat = clipLat(Math.toDegrees(satPos.latitude))
val osmLon = clipLon(Math.toDegrees(satPos.longitude))
val osmPos = GeoPos(osmLat, osmLon)
val qthLoc = QthConverter.positionToQth(osmPos.latitude, osmPos.longitude) ?: "-- --"
val satData = MapData(
satellite, satellite.params.catnum, satellite.params.name, satPos.range,
satPos.altitude, satPos.getOrbitalVelocity(), qthLoc, osmPos
)
_satData.postValue(satData)
}
private fun clipLat(latitude: Double): Double {
return clip(latitude, -85.05, 85.05)
}
private fun clipLon(longitude: Double): Double {
var result = longitude
while (result < -180.0) result += 360.0
while (result > 180.0) result -= 360.0
return clip(result, -180.0, 180.0)
}
private fun clip(currentValue: Double, minValue: Double, maxValue: Double): Double {
return min(max(currentValue, minValue), maxValue)
}
}
@@ -0,0 +1,150 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.passesScreen
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.ItemPassGeoBinding
import com.rtbishop.look4sat.databinding.ItemPassLeoBinding
import com.rtbishop.look4sat.domain.predict.SatPass
import java.text.SimpleDateFormat
import java.util.*
class PassesAdapter(private val isUTC: Boolean, private val clickListener: PassesClickListener) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val diffCallback = object : DiffUtil.ItemCallback<SatPass>() {
override fun areItemsTheSame(oldItem: SatPass, newItem: SatPass): Boolean {
return oldItem.catNum == newItem.catNum && oldItem.aosTime == newItem.aosTime
}
override fun areContentsTheSame(oldItem: SatPass, newItem: SatPass): Boolean {
return oldItem.progress == newItem.progress
}
}
private val differ = AsyncListDiffer(this, diffCallback)
interface PassesClickListener {
fun navigateToPass(satPass: SatPass)
}
fun submitList(passes: List<SatPass>) {
differ.submitList(passes)
}
override fun getItemCount() = differ.currentList.size
override fun getItemViewType(position: Int): Int {
return if (differ.currentList[position].isDeepSpace) 1
else 0
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == 0) {
SatPassLeoHolder.from(parent)
} else {
SatPassGeoHolder.from(parent)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder.itemViewType == 0) {
(holder as SatPassLeoHolder).bind(differ.currentList[position], clickListener, isUTC)
} else {
(holder as SatPassGeoHolder).bind(differ.currentList[position], clickListener)
}
}
class SatPassLeoHolder private constructor(private val binding: ItemPassLeoBinding) :
RecyclerView.ViewHolder(binding.root) {
private val satIdFormat = itemView.context.getString(R.string.pass_satId)
private val tcaAzFormat = itemView.context.getString(R.string.pass_tcaAz)
private val aosAzFormat = itemView.context.getString(R.string.pass_aosAz)
private val maxElFormat = itemView.context.getString(R.string.pass_maxEl)
private val losAzFormat = itemView.context.getString(R.string.pass_losAz)
private val startTimeFormat = itemView.context.getString(R.string.pass_startTime)
private val endTimeFormat = itemView.context.getString(R.string.pass_endTime)
private val timeZoneUTC = TimeZone.getTimeZone("UTC")
private val startFormat = SimpleDateFormat(startTimeFormat, Locale.getDefault())
private val endFormat = SimpleDateFormat(endTimeFormat, Locale.getDefault())
fun bind(satPass: SatPass, listener: PassesClickListener, shouldUseUTC: Boolean) {
binding.apply {
if (shouldUseUTC) {
startFormat.timeZone = timeZoneUTC
endFormat.timeZone = timeZoneUTC
}
passLeoName.text = satPass.name
passLeoId.text = String.format(satIdFormat, satPass.catNum)
passLeoAos.text = String.format(aosAzFormat, satPass.aosAzimuth)
passLeoElev.text = String.format(maxElFormat, satPass.maxElevation)
passLeoLos.text = String.format(losAzFormat, satPass.losAzimuth)
passLeoStart.text = startFormat.format(Date(satPass.aosTime))
passLeoTca.text = String.format(tcaAzFormat, satPass.tcaAzimuth)
passLeoEnd.text = endFormat.format(Date(satPass.losTime))
passLeoProgress.progress = satPass.progress
}
itemView.setOnClickListener {
listener.navigateToPass(satPass)
}
}
companion object {
fun from(parent: ViewGroup): SatPassLeoHolder {
val inflater = LayoutInflater.from(parent.context)
return SatPassLeoHolder(ItemPassLeoBinding.inflate(inflater, parent, false))
}
}
}
class SatPassGeoHolder private constructor(private val binding: ItemPassGeoBinding) :
RecyclerView.ViewHolder(binding.root) {
private val satIdFormat = itemView.context.getString(R.string.pass_satId)
private val azFormat = itemView.context.getString(R.string.pat_azimuth)
private val altFormat = itemView.context.getString(R.string.pat_altitude)
private val elevFormat = itemView.context.getString(R.string.pat_elevation)
fun bind(satPass: SatPass, listener: PassesClickListener) {
binding.apply {
passGeoName.text = satPass.name
passGeoId.text = String.format(satIdFormat, satPass.catNum)
passGeoAz.text = String.format(azFormat, satPass.tcaAzimuth)
passGeoAlt.text = String.format(altFormat, satPass.altitude)
passGeoEl.text = String.format(elevFormat, satPass.maxElevation)
}
itemView.setOnClickListener {
listener.navigateToPass(satPass)
}
}
companion object {
fun from(parent: ViewGroup): SatPassGeoHolder {
val inflater = LayoutInflater.from(parent.context)
return SatPassGeoHolder(ItemPassGeoBinding.inflate(inflater, parent, false))
}
}
}
}
@@ -0,0 +1,137 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.passesScreen
import android.Manifest
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.FragmentPassesBinding
import com.rtbishop.look4sat.domain.predict.SatPass
import com.rtbishop.look4sat.domain.model.DataState
import com.rtbishop.look4sat.presentation.ItemDivider
import com.rtbishop.look4sat.presentation.navigateSafe
import com.rtbishop.look4sat.presentation.toTimerString
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
@AndroidEntryPoint
class PassesFragment : Fragment(R.layout.fragment_passes), PassesAdapter.PassesClickListener {
private val passesViewModel: PassesViewModel by viewModels()
private val permReqContract = ActivityResultContracts.RequestMultiplePermissions()
private val locPermFine = Manifest.permission.ACCESS_FINE_LOCATION
private val locPermCoarse = Manifest.permission.ACCESS_COARSE_LOCATION
private val locPermReq = registerForActivityResult(permReqContract) { permissions ->
when {
permissions[locPermFine] == true -> passesViewModel.triggerInitialSetup()
permissions[locPermCoarse] == true -> passesViewModel.triggerInitialSetup()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupComponents(view)
}
private fun setupComponents(view: View) {
val passesAdapter = PassesAdapter(passesViewModel.shouldUseUTC(), this)
val binding = FragmentPassesBinding.bind(view).apply {
passesRecycler.apply {
setHasFixedSize(true)
adapter = passesAdapter
isVerticalScrollBarEnabled = false
layoutManager = LinearLayoutManager(context)
(itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
addItemDecoration(ItemDivider(R.drawable.rec_divider_dark))
}
passesRefresh.setOnClickListener { passesViewModel.forceCalculation() }
}
passesViewModel.passes.observe(viewLifecycleOwner, { passesResult ->
handleNewPasses(passesResult, passesAdapter, binding)
})
passesViewModel.isFirstLaunchDone.observe(viewLifecycleOwner, { setupDone ->
if (!setupDone) locPermReq.launch(arrayOf(locPermFine, locPermCoarse))
})
}
private fun handleNewPasses(
dataState: DataState<List<SatPass>>,
passesAdapter: PassesAdapter,
binding: FragmentPassesBinding
) {
when (dataState) {
is DataState.Success -> {
passesAdapter.submitList(dataState.data)
binding.apply {
passesError.visibility = View.INVISIBLE
passesProgress.visibility = View.INVISIBLE
passesRecycler.visibility = View.VISIBLE
}
tickMainTimer(dataState.data, binding)
}
is DataState.Loading -> {
binding.apply {
passesTimer.text = 0L.toTimerString()
passesError.visibility = View.INVISIBLE
passesRecycler.visibility = View.INVISIBLE
passesProgress.visibility = View.VISIBLE
}
}
else -> {
binding.apply {
passesTimer.text = 0L.toTimerString()
passesProgress.visibility = View.INVISIBLE
passesRecycler.visibility = View.INVISIBLE
passesError.visibility = View.VISIBLE
}
}
}
}
private fun tickMainTimer(passes: List<SatPass>, binding: FragmentPassesBinding) {
if (passes.isNotEmpty()) {
val timeNow = System.currentTimeMillis()
try {
val nextPass = passes.first { it.aosTime.minus(timeNow) > 0 }
val millisBeforeStart = nextPass.aosTime.minus(timeNow)
binding.passesTimer.text = millisBeforeStart.toTimerString()
} catch (e: NoSuchElementException) {
val lastPass = passes.last()
val millisBeforeEnd = lastPass.losTime.minus(timeNow)
binding.passesTimer.text = millisBeforeEnd.toTimerString()
}
} else {
binding.passesTimer.text = 0L.toTimerString()
}
}
override fun navigateToPass(satPass: SatPass) {
if (satPass.progress < 100) {
val bundle = bundleOf("catNum" to satPass.catNum, "aosTime" to satPass.aosTime)
findNavController().navigateSafe(R.id.action_passes_to_radar, bundle)
}
}
}
@@ -0,0 +1,122 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.passesScreen
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rtbishop.look4sat.domain.predict.Predictor
import com.rtbishop.look4sat.domain.predict.SatPass
import com.rtbishop.look4sat.domain.model.DataState
import com.rtbishop.look4sat.domain.DataRepository
import com.rtbishop.look4sat.framework.PreferencesSource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import java.util.*
import javax.inject.Inject
@HiltViewModel
class PassesViewModel @Inject constructor(
private val dataRepository: DataRepository,
private val predictor: Predictor,
private val preferences: PreferencesSource
) : ViewModel() {
private val _passes = MutableLiveData<DataState<List<SatPass>>>(DataState.Loading)
private val _isFirstLaunchDone = MutableLiveData<Boolean>()
private var passesProcessing: Job? = null
val passes: LiveData<DataState<List<SatPass>>> = _passes
val isFirstLaunchDone: LiveData<Boolean> = _isFirstLaunchDone
init {
if (preferences.isSetupDone()) {
viewModelScope.launch {
_passes.postValue(DataState.Loading)
val timeNow = System.currentTimeMillis()
val satellites = dataRepository.getSelectedSatellites()
val stationPos = preferences.loadStationPosition()
val hoursAhead = preferences.getHoursAhead()
val minElev = preferences.getMinElevation()
predictor.triggerCalculation(satellites, stationPos, timeNow, hoursAhead, minElev)
}
} else {
_isFirstLaunchDone.value = false
}
viewModelScope.launch {
predictor.passes.collect { passes ->
passesProcessing?.cancelAndJoin()
passesProcessing = viewModelScope.launch { tickPasses(passes) }
}
}
}
fun triggerInitialSetup() {
preferences.updatePositionFromGPS()
viewModelScope.launch {
_passes.postValue(DataState.Loading)
val satellites = dataRepository.getSelectedSatellites()
val stationPos = preferences.loadStationPosition()
val hoursAhead = preferences.getHoursAhead()
val minElev = preferences.getMinElevation()
dataRepository.updateDataFromWeb()
dataRepository.updateSelection(isSelected = true)
predictor.forceCalculation(satellites, stationPos, Date().time, hoursAhead, minElev)
preferences.setSetupDone()
_isFirstLaunchDone.value = true
}
}
fun forceCalculation() {
viewModelScope.launch {
_passes.postValue(DataState.Loading)
passesProcessing?.cancelAndJoin()
val timeNow = System.currentTimeMillis()
val satellites = dataRepository.getSelectedSatellites()
val stationPos = preferences.loadStationPosition()
val hoursAhead = preferences.getHoursAhead()
val minElev = preferences.getMinElevation()
predictor.forceCalculation(satellites, stationPos, timeNow, hoursAhead, minElev)
}
}
fun shouldUseUTC(): Boolean {
return preferences.shouldUseUTC()
}
private suspend fun tickPasses(passes: List<SatPass>) = withContext(Dispatchers.Default) {
var currentPasses = passes
while (isActive) {
val timeNow = System.currentTimeMillis()
currentPasses.forEach { pass ->
if (!pass.isDeepSpace) {
val timeStart = pass.aosTime
if (timeNow > timeStart) {
val deltaNow = timeNow.minus(timeStart).toFloat()
val deltaTotal = pass.losTime.minus(timeStart).toFloat()
pass.progress = ((deltaNow / deltaTotal) * 100).toInt()
}
}
}
currentPasses = currentPasses.filter { it.progress < 100 }
_passes.postValue(DataState.Success(currentPasses.map { it.copy() }))
delay(1000)
}
}
}
@@ -0,0 +1,22 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.radarScreen
import com.rtbishop.look4sat.domain.predict.SatPos
data class RadarData(val satPos: SatPos, val satTrack: List<SatPos> = emptyList())
@@ -0,0 +1,167 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.radarScreen
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.FragmentRadarBinding
import com.rtbishop.look4sat.framework.PreferencesSource
import com.rtbishop.look4sat.domain.predict.SatPass
import com.rtbishop.look4sat.domain.predict.SatPos
import com.rtbishop.look4sat.presentation.ItemDivider
import com.rtbishop.look4sat.presentation.navigateSafe
import com.rtbishop.look4sat.presentation.toTimerString
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class RadarFragment : Fragment(R.layout.fragment_radar) {
@Inject
lateinit var preferences: PreferencesSource
private val viewModel: RadarViewModel by viewModels()
private var radarView: RadarView? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
FragmentRadarBinding.bind(view).apply {
val transAdapter = TransmittersAdapter()
radarRecycler.apply {
setHasFixedSize(true)
adapter = transAdapter
isVerticalScrollBarEnabled = false
layoutManager = LinearLayoutManager(context)
(itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
addItemDecoration(ItemDivider(R.drawable.rec_divider_dark))
}
setupObservers(transAdapter, this)
}
}
override fun onResume() {
super.onResume()
viewModel.enableSensor()
}
override fun onPause() {
super.onPause()
viewModel.disableSensor()
}
private fun setupObservers(
transmittersAdapter: TransmittersAdapter,
binding: FragmentRadarBinding
) {
val catNum = requireArguments().getInt("catNum")
val aosTime = requireArguments().getLong("aosTime")
viewModel.getPass(catNum, aosTime).observe(viewLifecycleOwner) { pass ->
radarView = RadarView(requireContext()).apply {
setShowAim(preferences.shouldUseCompass())
setScanning(preferences.shouldShowSweep())
}
binding.radarFrame.addView(radarView)
viewModel.radarData.observe(viewLifecycleOwner, { passData ->
radarView?.setPosition(passData.satPos)
radarView?.setPositions(passData.satTrack)
setPassText(pass, passData.satPos, binding)
})
viewModel.transmitters.observe(viewLifecycleOwner, { list ->
if (list.isNotEmpty()) {
transmittersAdapter.submitList(list)
binding.radarRecycler.visibility = View.VISIBLE
binding.radarRecyclerMsg.visibility = View.INVISIBLE
} else {
binding.radarRecycler.visibility = View.INVISIBLE
binding.radarRecyclerMsg.visibility = View.VISIBLE
}
radarView?.invalidate()
})
viewModel.orientation.observe(viewLifecycleOwner, { orientation ->
radarView?.setOrientation(
orientation.first,
orientation.second,
orientation.third
)
})
binding.radarToMapButton.setOnClickListener {
val bundle = bundleOf("catNum" to pass.catNum)
findNavController().navigateSafe(R.id.action_radar_to_map, bundle)
}
}
// binding.radarNotifyButton.setOnClickListener {
// this.context?.let { context ->
//
// val choicesList = arrayOf(
// getString(R.string.notification_on_start_pass),
// getString(R.string.notification_5_min_before),
// getString(R.string.notification_10_min_before),
// getString(R.string.notification_15_min_before),
// )
//
// MaterialAlertDialogBuilder(context)
// .setTitle(getString(R.string.notification_title))
// .setSingleChoiceItems(choicesList, -1) { dialog, which ->
// // TODO in this place should set a notification by NotificationBuilder
// Toast.makeText(context, "Reminder was saved", Toast.LENGTH_SHORT).show()
// dialog.dismiss()
// }
// .setNegativeButton(getString(R.string.btn_cancel)) { _, _ ->
// // noop
// }
// .show()
// }
// }
}
private fun setPassText(satPass: SatPass, satPos: SatPos, binding: FragmentRadarBinding) {
val timeNow = System.currentTimeMillis()
val polarAz = getString(R.string.pat_azimuth)
val polarEl = getString(R.string.pat_elevation)
val polarRng = getString(R.string.pat_distance)
val polarAlt = getString(R.string.pat_altitude)
binding.radarAz.text = String.format(polarAz, Math.toDegrees(satPos.azimuth))
binding.radarEl.text = String.format(polarEl, Math.toDegrees(satPos.elevation))
binding.radarDst.text = String.format(polarRng, satPos.range)
binding.radarAlt.text = String.format(polarAlt, satPos.altitude)
binding.radarName.text = satPass.name
if (!satPass.isDeepSpace) {
if (timeNow < satPass.aosTime) {
val millisBeforeStart = satPass.aosTime.minus(timeNow)
binding.radarTimer.text = millisBeforeStart.toTimerString()
} else {
val millisBeforeEnd = satPass.losTime.minus(timeNow)
binding.radarTimer.text = millisBeforeEnd.toTimerString()
if (timeNow > satPass.losTime) {
binding.radarTimer.text = 0L.toTimerString()
findNavController().navigateSafe(R.id.action_radar_to_passes)
}
}
} else {
binding.radarTimer.text = 0L.toTimerString()
}
}
}
@@ -0,0 +1,265 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.radarScreen
import android.content.Context
import android.graphics.*
import android.view.View
import androidx.core.content.ContextCompat
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.domain.predict.SatPos
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin
class RadarView(context: Context) : View(context) {
private val defaultColor = ContextCompat.getColor(context, R.color.themeLight)
private val scale = resources.displayMetrics.density
private val radarWidth = resources.displayMetrics.widthPixels
private val radarRadius = radarWidth * 0.48f
private val piDiv2 = Math.PI / 2.0
private val strokeSize = scale * 2f
private var position: SatPos? = null
private var positions: List<SatPos> = emptyList()
private var radarColor = ContextCompat.getColor(context, R.color.greyLight)
private var radarCircleNum = 3
private var radarPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = radarColor
style = Paint.Style.STROKE
strokeWidth = strokeSize
}
private var shouldShowSweep = true
private var sweepColor = defaultColor
private var sweepDegrees = 0f
private var sweepSpeed = 30.0f
private var sweepPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = sweepColor
}
private var shouldShowBeacons = true
private var beaconColor = defaultColor
private var beaconSize = scale * 7f
private var beaconPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = beaconColor
style = Paint.Style.FILL
}
private var radarTextSize = scale * 16f
private var radarTextColor = defaultColor
private var radarTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = radarTextColor
textSize = radarTextSize
}
private var isTrackCreated = false
private val trackPath: Path = Path()
private var trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = strokeSize
}
private val arrowPath = Path()
private var arrowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = ContextCompat.getColor(context, R.color.themeLight)
style = Paint.Style.FILL
strokeWidth = strokeSize
}
private var shouldShowAim = true
private var aimColor = Color.RED
private var aimPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = aimColor
style = Paint.Style.STROKE
strokeWidth = strokeSize
}
private var shouldRotateRadar = true
private var azimuth: Float = 0f
private var pitch: Float = 0f
private var roll: Float = 0f
fun setScanning(isScanning: Boolean) {
shouldShowSweep = isScanning
}
fun setPosition(position: SatPos) {
this.position = position
}
fun setPositions(positions: List<SatPos>) {
this.positions = positions
}
fun setShowAim(showAim: Boolean) {
shouldShowAim = showAim
}
fun setOrientation(azimuth: Float, pitch: Float, roll: Float) {
this.azimuth = azimuth
this.pitch = pitch
this.roll = roll
if (shouldRotateRadar) {
this.rotation = -azimuth
}
}
override fun onDraw(canvas: Canvas) {
val radarWidth = width - paddingLeft - paddingRight
val radarHeight = height - paddingTop - paddingBottom
val radarRadius = min(width, height) * 0.49f
val cx = paddingLeft + radarWidth / 2f
val cy = paddingTop + radarHeight / 2f
if (positions.isNotEmpty() && !isTrackCreated) {
createPassTrajectory()
createPassTrajectoryArrow()
isTrackCreated = true
}
canvas.drawColor(ContextCompat.getColor(context, R.color.greyDark))
drawRadarCircle(canvas, cx, cy, radarRadius)
drawRadarCross(canvas, cx, cy, radarRadius)
drawRadarText(canvas, cx, radarRadius)
canvas.translate(cx, cy)
if (positions.isNotEmpty()) {
canvas.drawPath(trackPath, trackPaint)
canvas.drawPath(trackPath, arrowPaint)
}
if (shouldShowBeacons) {
drawSatellite(canvas)
}
if (shouldShowAim) {
drawCrosshair(canvas, azimuth, pitch)
}
if (shouldShowSweep) {
canvas.translate(-cx, -cy)
drawRadarSweep(canvas, cx, cy, radarRadius)
sweepDegrees = (sweepDegrees + 360 / sweepSpeed / 60) % 360
}
invalidate()
}
private fun drawRadarCircle(canvas: Canvas, cx: Float, cy: Float, radius: Float) {
for (i in 0 until radarCircleNum) {
canvas.drawCircle(cx, cy, radius - radius / radarCircleNum * i, radarPaint)
}
}
private fun drawRadarCross(canvas: Canvas, cx: Float, cy: Float, radius: Float) {
canvas.drawLine(cx - radius, cy, cx + radius, cy, radarPaint)
canvas.drawLine(cx, cy - radius, cx, cy + radius, radarPaint)
}
private fun drawRadarText(canvas: Canvas, cx: Float, radius: Float) {
for (i in 0 until radarCircleNum) {
val degText = " ${(90 / radarCircleNum) * (radarCircleNum - i)}°"
canvas.drawText(degText, cx, radius - radius / radarCircleNum * i, radarTextPaint)
}
}
private fun drawSatellite(canvas: Canvas) {
position?.let { satPos ->
if (satPos.elevation > 0) {
val satX = sph2CartX(satPos.azimuth, satPos.elevation, radarRadius.toDouble())
val satY = sph2CartY(satPos.azimuth, satPos.elevation, radarRadius.toDouble())
canvas.drawCircle(satX, -satY, beaconSize, beaconPaint)
}
}
}
private fun drawCrosshair(canvas: Canvas, azimuth: Float, pitch: Float) {
val azimuthRad = Math.toRadians(azimuth.toDouble())
val tmpElevation = Math.toRadians(pitch.toDouble())
val elevationRad = if (tmpElevation > 0.0) 0.0 else tmpElevation
val crossX = sph2CartX(azimuthRad, -elevationRad, radarRadius.toDouble())
val crossY = sph2CartY(azimuthRad, -elevationRad, radarRadius.toDouble())
canvas.drawLine(crossX - radarTextSize, -crossY, crossX + radarTextSize, -crossY, aimPaint)
canvas.drawLine(crossX, -crossY - radarTextSize, crossX, -crossY + radarTextSize, aimPaint)
canvas.drawCircle(crossX, -crossY, radarTextSize / 2, aimPaint)
}
private fun sph2CartX(azimuth: Double, elevation: Double, r: Double): Float {
val radius = r * (piDiv2 - elevation) / piDiv2
return (radius * cos(piDiv2 - azimuth)).toFloat()
}
private fun sph2CartY(azimuth: Double, elevation: Double, r: Double): Float {
val radius = r * (piDiv2 - elevation) / piDiv2
return (radius * sin(piDiv2 - azimuth)).toFloat()
}
private fun createPassTrajectory() {
positions.forEachIndexed { index, satPos ->
val passX = sph2CartX(satPos.azimuth, satPos.elevation, radarRadius.toDouble())
val passY = sph2CartY(satPos.azimuth, satPos.elevation, radarRadius.toDouble())
if (index == 0) {
trackPath.moveTo(passX, -passY)
} else {
trackPath.lineTo(passX, -passY)
}
}
}
private fun createPassTrajectoryArrow() {
val radius = beaconSize
val sides = 3
val angle = 2.0 * Math.PI / sides
arrowPath.moveTo((radius * cos(angle)).toFloat(), (radius * sin(angle)).toFloat())
for (i in 1 until sides) {
val x = (radius * cos(angle - angle * i)).toFloat()
val y = (radius * sin(angle - angle * i)).toFloat()
arrowPath.lineTo(x, y)
}
arrowPath.close()
val trackLength = PathMeasure(trackPath, false).length
val quarter = trackLength / 4f
val center = trackLength / 2f
val effect = PathDashPathEffect(arrowPath, center, quarter, PathDashPathEffect.Style.ROTATE)
arrowPaint.pathEffect = effect
}
private fun drawRadarSweep(canvas: Canvas, cx: Float, cy: Float, radius: Float) {
val sweepGradient = SweepGradient(
cx,
cy,
intArrayOf(
Color.TRANSPARENT,
changeAlpha(sweepColor, 0),
changeAlpha(sweepColor, 164),
changeAlpha(sweepColor, 255),
changeAlpha(sweepColor, 255)
),
floatArrayOf(0.0f, 0.55f, 0.996f, 0.999f, 1f)
)
sweepPaint.shader = sweepGradient
canvas.rotate(-90 + sweepDegrees, cx, cy)
canvas.drawCircle(cx, cy, radius, sweepPaint)
}
private fun changeAlpha(color: Int, alpha: Int): Int {
val red = Color.red(color)
val green = Color.green(color)
val blue = Color.blue(color)
return Color.argb(alpha, red, green, blue)
}
}
@@ -0,0 +1,120 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.radarScreen
import androidx.lifecycle.*
import com.rtbishop.look4sat.domain.DataReporter
import com.rtbishop.look4sat.domain.DataRepository
import com.rtbishop.look4sat.domain.predict.Predictor
import com.rtbishop.look4sat.domain.predict.SatPass
import com.rtbishop.look4sat.domain.predict.SatPos
import com.rtbishop.look4sat.domain.model.Transmitter
import com.rtbishop.look4sat.framework.OrientationSource
import com.rtbishop.look4sat.framework.PreferencesSource
import com.rtbishop.look4sat.presentation.round
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject
@HiltViewModel
class RadarViewModel @Inject constructor(
private val orientationSource: OrientationSource,
private val preferences: PreferencesSource,
private val predictor: Predictor,
private val dataRepository: DataRepository,
private val dataReporter: DataReporter
) : ViewModel(), OrientationSource.OrientationListener {
private val stationPos = preferences.loadStationPosition()
private val _passData = MutableLiveData<RadarData>()
private val _transmitters = MutableLiveData<List<Transmitter>>()
private val _orientation = MutableLiveData<Triple<Float, Float, Float>>()
val radarData: LiveData<RadarData> = _passData
val transmitters: LiveData<List<Transmitter>> = _transmitters
val orientation: LiveData<Triple<Float, Float, Float>> = _orientation
fun getPass(catNum: Int, aosTime: Long) = liveData {
predictor.passes.collect { passes ->
val pass = passes.find { it.catNum == catNum && it.aosTime == aosTime }
pass?.let { satPass ->
emit(satPass)
sendPassData(satPass)
processTransmitters(satPass)
}
}
}
fun enableSensor() {
if (preferences.shouldUseCompass()) orientationSource.startListening(this)
}
fun disableSensor() {
if (preferences.shouldUseCompass()) orientationSource.stopListening()
}
override fun onOrientationChanged(azimuth: Float, pitch: Float, roll: Float) {
_orientation.value = Triple(azimuth + preferences.getMagDeclination(), pitch, roll)
}
private fun sendPassData(satPass: SatPass) {
viewModelScope.launch {
var satTrack: List<SatPos> = emptyList()
if (!satPass.isDeepSpace) {
val startDate = satPass.aosTime
val endDate = satPass.losTime
satTrack = predictor.getSatTrack(satPass.satellite, stationPos, startDate, endDate)
}
while (isActive) {
val satPos = predictor.getSatPos(satPass.satellite, stationPos, Date().time)
if (preferences.isRotatorEnabled()) {
val server = preferences.getRotatorServer().first
val port = preferences.getRotatorServer().second
val azimuth = Math.toDegrees(satPos.azimuth).round(1)
val elevation = Math.toDegrees(satPos.elevation).round(1)
dataReporter.reportRotation(server, port, azimuth, elevation)
}
_passData.postValue(RadarData(satPos, satTrack))
delay(1000)
}
}
}
private fun processTransmitters(satPass: SatPass) {
viewModelScope.launch {
val transmitters = dataRepository.getTransmitters(satPass.catNum)
while (isActive) {
val satPos = predictor.getSatPos(satPass.satellite, stationPos, Date().time)
val copiedList = transmitters.map { it.copy() }
copiedList.forEach { transmitter ->
transmitter.downlink?.let {
transmitter.downlink = satPos.getDownlinkFreq(it)
}
transmitter.uplink?.let {
transmitter.uplink = satPos.getUplinkFreq(it)
}
}
_transmitters.postValue(copiedList.map { it.copy() })
delay(1000)
}
}
}
}
@@ -0,0 +1,110 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.radarScreen
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.ItemTransBinding
import com.rtbishop.look4sat.domain.model.Transmitter
import java.util.*
class TransmittersAdapter : RecyclerView.Adapter<TransmittersAdapter.TransHolder>() {
private val diffCallback = object : DiffUtil.ItemCallback<Transmitter>() {
override fun areItemsTheSame(oldItem: Transmitter, newItem: Transmitter): Boolean {
return oldItem.uuid == newItem.uuid
}
override fun areContentsTheSame(oldItem: Transmitter, newItem: Transmitter): Boolean {
return oldItem.downlink == newItem.downlink
}
}
private val differ = AsyncListDiffer(this, diffCallback)
fun submitList(transmitters: List<Transmitter>) {
differ.submitList(transmitters)
}
override fun getItemCount() = differ.currentList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TransHolder {
return TransHolder.from(parent)
}
override fun onBindViewHolder(holder: TransHolder, position: Int) {
holder.bind(differ.currentList[position])
}
class TransHolder private constructor(private val binding: ItemTransBinding) :
RecyclerView.ViewHolder(binding.root) {
private val divider = 1000000f
private val strNo = itemView.context.getString(R.string.no)
private val strYes = itemView.context.getString(R.string.yes)
private val mode = itemView.context.getString(R.string.trans_mode)
private val formatLink = itemView.context.getString(R.string.trans_link_low)
private val formatLinkNull = itemView.context.getString(R.string.trans_no_link)
private val isInverted = itemView.context.getString(R.string.trans_inverted)
fun bind(transmitter: Transmitter) {
binding.transDesc.text = transmitter.info
transmitter.downlink.let { downlink ->
if (downlink != null) {
val downlinkFreq = downlink / divider
binding.transDownlink.text =
String.format(Locale.ENGLISH, formatLink, downlinkFreq)
} else {
binding.transDownlink.text = formatLinkNull
}
}
transmitter.uplink.let { uplink ->
if (uplink != null) {
val uplinkFreq = uplink / divider
binding.transUplink.text = String.format(Locale.ENGLISH, formatLink, uplinkFreq)
} else {
binding.transUplink.text = formatLinkNull
}
}
if (transmitter.mode != null) {
binding.transMode.text = String.format(mode, transmitter.mode)
} else {
binding.transMode.text = String.format(mode, strNo)
}
if (transmitter.isInverted) {
binding.transInverted.text = String.format(isInverted, strYes)
} else {
binding.transInverted.text = String.format(isInverted, strNo)
}
}
companion object {
fun from(parent: ViewGroup): TransHolder {
val inflater = LayoutInflater.from(parent.context)
return TransHolder(ItemTransBinding.inflate(inflater, parent, false))
}
}
}
}
@@ -0,0 +1,124 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.settingsScreen
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.InputType
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.google.android.material.snackbar.Snackbar
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.framework.PreferencesSource
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class SettingsFragment : PreferenceFragmentCompat() {
@Inject
lateinit var preferences: PreferencesSource
private val permReqContract = ActivityResultContracts.RequestMultiplePermissions()
private val locPermFine = Manifest.permission.ACCESS_FINE_LOCATION
private val locPermCoarse = Manifest.permission.ACCESS_COARSE_LOCATION
private val locPermReq = registerForActivityResult(permReqContract) { permissions ->
when {
permissions[locPermFine] == true -> updatePositionFromGPS()
permissions[locPermCoarse] == true -> updatePositionFromGPS()
else -> showSnack(getString(R.string.pref_pos_gps_error))
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preference, rootKey)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
findPreference<Preference>(PreferencesSource.keyPositionGPS)?.apply {
setOnPreferenceClickListener {
updatePositionFromGPS()
return@setOnPreferenceClickListener true
}
}
findPreference<Preference>(PreferencesSource.keyPositionQTH)?.apply {
setOnPreferenceChangeListener { _, newValue ->
updatePositionFromQth(newValue.toString())
}
}
findPreference<EditTextPreference>(PreferencesSource.keyRotatorAddress)?.apply {
setOnPreferenceChangeListener { _, newValue ->
val ip4 = "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\.(?!\$)|\$)){4}\$"
if (newValue.toString().matches(ip4.toRegex())) {
return@setOnPreferenceChangeListener true
} else {
showSnack(getString(R.string.tracking_rotator_address_invalid))
return@setOnPreferenceChangeListener false
}
}
}
findPreference<EditTextPreference>(PreferencesSource.keyRotatorPort)?.apply {
setOnBindEditTextListener { it.inputType = InputType.TYPE_CLASS_NUMBER }
setOnPreferenceChangeListener { _, newValue ->
val portValue = newValue.toString()
if (portValue.isNotEmpty() && portValue.toInt() in 1024..65535) {
return@setOnPreferenceChangeListener true
} else {
showSnack(getString(R.string.tracking_rotator_port_invalid))
return@setOnPreferenceChangeListener false
}
}
}
}
private fun updatePositionFromQth(qthString: String): Boolean {
return if (preferences.updatePositionFromQTH(qthString)) {
showSnack(getString(R.string.pref_pos_success))
true
} else {
showSnack(getString(R.string.pref_pos_qth_error))
false
}
}
private fun updatePositionFromGPS() {
val locPermString = Manifest.permission.ACCESS_FINE_LOCATION
val locPermResult = ContextCompat.checkSelfPermission(requireContext(), locPermString)
if (locPermResult == PackageManager.PERMISSION_GRANTED) {
if (preferences.updatePositionFromGPS()) {
showSnack(getString(R.string.pref_pos_success))
} else {
showSnack(getString(R.string.pref_pos_gps_null))
}
} else locPermReq.launch(arrayOf(locPermFine, locPermCoarse))
}
private fun showSnack(message: String) {
Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT).show()
}
}
@@ -0,0 +1,70 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.sourcesScreen
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.widget.doOnTextChanged
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.databinding.ItemSourceBinding
import com.rtbishop.look4sat.framework.model.Source
class SourcesAdapter(private val sources: MutableList<Source> = mutableListOf()) :
RecyclerView.Adapter<SourcesAdapter.TleSourceHolder>() {
fun getSources(): List<Source> {
return sources.filter { it.sourceUrl.contains("https://") }
}
fun setSources(list: List<Source>) {
sources.clear()
sources.addAll(list)
}
fun addSource() {
sources.add(Source())
notifyItemInserted(itemCount - 1)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TleSourceHolder {
val binding = ItemSourceBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return TleSourceHolder(binding)
}
override fun onBindViewHolder(holder: TleSourceHolder, position: Int) {
holder.bind(sources[position])
}
override fun getItemCount(): Int {
return sources.size
}
inner class TleSourceHolder(private val binding: ItemSourceBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(source: Source) {
binding.sourceUrl.setText(source.sourceUrl)
binding.sourceUrl.doOnTextChanged { txt, _, _, _ -> source.sourceUrl = txt.toString() }
binding.sourceBtn.setOnClickListener {
sources.remove(source)
notifyItemRemoved(adapterPosition)
}
}
}
}
@@ -0,0 +1,67 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2021 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.presentation.sourcesScreen
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.DialogSourcesBinding
import com.rtbishop.look4sat.framework.model.Source
import com.rtbishop.look4sat.presentation.setNavResult
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SourcesDialog : AppCompatDialogFragment() {
private val viewModel: SourcesViewModel by viewModels()
override fun onCreateView(inflater: LayoutInflater, group: ViewGroup?, state: Bundle?): View? {
return inflater.inflate(R.layout.dialog_sources, group, false)
}
override fun onViewCreated(view: View, state: Bundle?) {
super.onViewCreated(view, state)
viewModel.sources.observe(viewLifecycleOwner, { sources ->
val adapter = SourcesAdapter().apply { setSources(sources.map { Source(it) }) }
DialogSourcesBinding.bind(view).apply {
dialog?.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
sourcesRecycler.apply {
this.adapter = adapter
layoutManager = LinearLayoutManager(requireContext())
}
sourcesBtnAdd.setOnClickListener {
adapter.addSource()
}
sourcesBtnPos.setOnClickListener {
setNavResult("sources", adapter.getSources().map { it.sourceUrl })
dismiss()
}
sourcesBtnNeg.setOnClickListener { dismiss() }
}
})
}
}
@@ -0,0 +1,15 @@
package com.rtbishop.look4sat.presentation.sourcesScreen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.rtbishop.look4sat.domain.DataRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class SourcesViewModel @Inject constructor(dataRepository: DataRepository) : ViewModel() {
val sources = liveData {
emit(dataRepository.getWebSources())
}
}
@@ -1,97 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.repo
import android.content.ContentResolver
import android.net.Uri
import com.github.amsacode.predict4java.TLE
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
import com.rtbishop.look4sat.network.RemoteSource
import com.rtbishop.look4sat.persistence.LocalSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class DefaultRepository @Inject constructor(
private val resolver: ContentResolver,
private val localSource: LocalSource,
private val remoteSource: RemoteSource
) : Repository {
override suspend fun updateEntriesFromFile(tleUri: Uri) {
withContext(Dispatchers.IO) {
resolver.openInputStream(tleUri)?.use { stream ->
val tleList = TLE.importSat(stream)
val entries = tleList.map { SatEntry(it) }
localSource.clearEntries()
localSource.insertEntries(entries)
}
}
}
override suspend fun updateEntriesFromUrl(urlList: List<TleSource>) {
withContext(Dispatchers.IO) {
val streams = remoteSource.fetchTleStreams(urlList)
val entries = mutableListOf<SatEntry>()
streams.forEach {
val list = TLE.importSat(it).map { tle -> SatEntry(tle) }
entries.addAll(list)
}
localSource.clearEntries()
localSource.insertEntries(entries)
}
}
override suspend fun getAllEntries(): List<SatEntry> {
return localSource.getAllEntries()
}
override suspend fun getSelectedEntries(): List<SatEntry> {
return localSource.getSelectedEntries()
}
override suspend fun updateEntriesSelection(catNumList: List<Int>) {
localSource.updateEntriesSelection(catNumList)
}
////////////////////////////////////////////////////////////////////////////////////////////////
override suspend fun updateTransmitters() {
localSource.clearTransmitters()
localSource.insertTransmitters(remoteSource.fetchTransmitters())
}
override suspend fun getTransmittersByCatNum(catNum: Int): List<Transmitter> {
return localSource.getTransmittersByCatNum(catNum)
}
////////////////////////////////////////////////////////////////////////////////////////////////
override suspend fun updateSources(sources: List<TleSource>) {
localSource.clearSources()
localSource.insertSources(sources)
}
override suspend fun getSources(): List<TleSource> {
return localSource.getSources()
}
}
@@ -1,31 +0,0 @@
package com.rtbishop.look4sat.repo
import android.net.Uri
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.data.Transmitter
interface Repository {
suspend fun updateEntriesFromFile(tleUri: Uri)
suspend fun updateEntriesFromUrl(urlList: List<TleSource>)
suspend fun getAllEntries(): List<SatEntry>
suspend fun getSelectedEntries(): List<SatEntry>
suspend fun updateEntriesSelection(catNumList: List<Int>)
////////////////////////////////////////////////////////////////////////////////////////////////
suspend fun updateTransmitters()
suspend fun getTransmittersByCatNum(catNum: Int): List<Transmitter>
////////////////////////////////////////////////////////////////////////////////////////////////
suspend fun updateSources(sources: List<TleSource>)
suspend fun getSources(): List<TleSource>
}
@@ -1,222 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.rtbishop.look4sat.Look4SatApp
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.dagger.ViewModelFactory
import com.rtbishop.look4sat.data.Result
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.databinding.ActivityMainBinding
import com.rtbishop.look4sat.databinding.DrawerHeaderBinding
import com.rtbishop.look4sat.ui.fragments.TleSourcesDialogFragment
import com.rtbishop.look4sat.utility.Extensions.toast
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
class MainActivity : AppCompatActivity(), TleSourcesDialogFragment.SourcesSubmitListener {
private val pickFileReqCode = 1001
private val permissionsReqCode = 1000
private val permissions = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
@Inject
lateinit var viewModelFactory: ViewModelFactory
private lateinit var viewModel: SharedViewModel
private lateinit var mainBinding: ActivityMainBinding
private lateinit var drawerBinding: DrawerHeaderBinding
private lateinit var appBarConfig: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
mainBinding = ActivityMainBinding.inflate(layoutInflater)
drawerBinding = DrawerHeaderBinding.inflate(layoutInflater, mainBinding.navView, true)
setContentView(mainBinding.root)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
(application as Look4SatApp).appComponent.inject(this)
viewModel = ViewModelProvider(this, viewModelFactory).get(SharedViewModel::class.java)
setupComponents()
setupObservers()
setupDrawer()
viewModel.setDefaultTleSources()
if (!hasPermissions(this, permissions)) {
ActivityCompat.requestPermissions(this, permissions, permissionsReqCode)
}
}
@SuppressLint("SourceLockedOrientationActivity")
private fun setupComponents() {
val navController = findNavController(R.id.nav_host)
val toolbar = mainBinding.includeAppBar.toolbar
setSupportActionBar(toolbar)
appBarConfig = AppBarConfiguration(
setOf(R.id.nav_pass_list, R.id.nav_map_view),
mainBinding.drawerLayout
)
setupActionBarWithNavController(navController, appBarConfig)
mainBinding.navView.setupWithNavController(navController)
navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.nav_pass_list -> {
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
toolbar.visibility = View.VISIBLE
mainBinding.includeAppBar.toolbarLayout.visibility = View.VISIBLE
}
R.id.nav_map_view -> {
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
toolbar.visibility = View.GONE
mainBinding.includeAppBar.toolbarLayout.visibility = View.GONE
}
R.id.nav_map_osm -> {
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
toolbar.visibility = View.GONE
mainBinding.includeAppBar.toolbarLayout.visibility = View.GONE
}
else -> {
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
toolbar.visibility = View.VISIBLE
mainBinding.includeAppBar.toolbarLayout.visibility = View.GONE
}
}
}
}
private fun setupObservers() {
viewModel.getGSP().observe(this, Observer { result ->
when (result) {
is Result.Success -> {
drawerBinding.drawerLatValue.text =
String.format(getString(R.string.pat_location), result.data.latitude)
drawerBinding.drawerLonValue.text =
String.format(getString(R.string.pat_location), result.data.longitude)
}
is Result.Error -> {
when (result.exception) {
is SecurityException ->
getString(R.string.err_no_permissions).toast(this)
is IllegalArgumentException ->
getString(R.string.update_loc_failure).toast(this)
}
}
}
})
viewModel.getUpdateStatus().observe(this, Observer { result ->
when (result) {
is Result.Success -> getString(R.string.import_data_success).toast(this)
is Result.Error -> getString(R.string.import_data_failure).toast(this)
}
})
}
private fun setupDrawer() {
drawerBinding.drawerBtnLoc.setOnClickListener {
viewModel.updatePosition()
it.lockButton()
}
drawerBinding.drawerBtnTleFile.setOnClickListener {
val openFileIntent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
}
startActivityForResult(openFileIntent, pickFileReqCode)
mainBinding.drawerLayout.closeDrawers()
it.lockButton()
}
drawerBinding.drawerBtnTleUrl.setOnClickListener {
TleSourcesDialogFragment(viewModel.getTleSources()).apply {
setSourcesListener(this@MainActivity)
show(supportFragmentManager, "TleSourcesDialog")
}
mainBinding.drawerLayout.closeDrawers()
it.lockButton()
}
drawerBinding.drawerBtnGithub.setOnClickListener {
val gitHubUrl = "https://github.com/rt-bishop/LookingSat"
val githubIntent = Intent(Intent.ACTION_VIEW, Uri.parse(gitHubUrl))
startActivity(githubIntent)
}
}
override fun onSourcesSubmit(list: List<TleSource>) {
viewModel.updateSatData(list)
}
private fun View.lockButton() {
lifecycleScope.launch {
this@lockButton.isEnabled = false
delay(3000)
this@lockButton.isEnabled = true
}
}
private fun hasPermissions(context: Context, permissions: Array<String>): Boolean =
permissions.all {
ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host)
return navController.navigateUp(appBarConfig) || super.onSupportNavigateUp()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == pickFileReqCode && resultCode == RESULT_OK) {
data?.data?.also { uri ->
viewModel.updateEntriesFromFile(uri)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
@@ -1,173 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui
import android.net.Uri
import androidx.lifecycle.*
import com.github.amsacode.predict4java.GroundStationPosition
import com.rtbishop.look4sat.data.Result
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.SatPass
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.repo.Repository
import com.rtbishop.look4sat.utility.PassPredictor
import com.rtbishop.look4sat.utility.PrefsManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SharedViewModel @Inject constructor(
private val prefsManager: PrefsManager,
private val repository: Repository
) : ViewModel() {
private val _satPassList = MutableLiveData<Result<MutableList<SatPass>>>()
private val _updateStatus = MutableLiveData<Result<Int>>()
private val _gsp = MutableLiveData<Result<GroundStationPosition>>().apply {
value = Result.Success(prefsManager.getPosition())
}
private var calculationJob: Job? = null
fun getTransmittersForSat(id: Int) = liveData { emit(repository.getTransmittersByCatNum(id)) }
fun getPassList(): LiveData<Result<MutableList<SatPass>>> = _satPassList
fun getUpdateStatus(): LiveData<Result<Int>> = _updateStatus
fun getGSP(): LiveData<Result<GroundStationPosition>> = _gsp
fun getCompass() = prefsManager.getCompass()
fun getRefreshRate() = prefsManager.getRefreshRate()
fun getHoursAhead() = prefsManager.getHoursAhead()
fun getMinElevation() = prefsManager.getMinElevation()
fun setPositionFromPref() = _gsp.postValue(Result.Success(prefsManager.getPosition()))
suspend fun getAllEntries() = repository.getAllEntries()
fun setPassPrefs(hoursAhead: Int, minEl: Double) {
prefsManager.setHoursAhead(hoursAhead)
prefsManager.setMinElevation(minEl)
}
fun updatePosition() {
val lastLoc = prefsManager.getLastKnownLocation()
if (lastLoc == null) {
_gsp.postValue(Result.Error(Exception()))
} else {
val gsp = GroundStationPosition(lastLoc.latitude, lastLoc.longitude, lastLoc.altitude)
_gsp.postValue(Result.Success(gsp))
}
}
fun updateEntriesFromFile(uri: Uri) {
viewModelScope.launch(Dispatchers.IO) {
try {
val selected = repository.getSelectedEntries().map { it.catNum }
repository.updateEntriesFromFile(uri)
repository.updateEntriesSelection(selected)
_updateStatus.postValue(Result.Success(0))
} catch (e: Exception) {
_updateStatus.postValue(Result.Error(e))
}
}
}
fun updateSatData(list: List<TleSource>) {
viewModelScope.launch(Dispatchers.IO) {
try {
val selected = repository.getSelectedEntries().map { it.catNum }
repository.updateSources(list)
repository.updateEntriesFromUrl(list)
repository.updateTransmitters()
repository.updateEntriesSelection(selected)
_updateStatus.postValue(Result.Success(0))
} catch (e: Exception) {
_updateStatus.postValue(Result.Error(e))
}
}
}
fun updateEntriesSelection(catNumList: MutableList<Int>) {
viewModelScope.launch(Dispatchers.IO) {
repository.updateEntriesSelection(catNumList)
calculatePasses()
}
}
fun calculatePasses() {
_satPassList.postValue(Result.InProgress)
calculationJob?.cancel()
var passList = mutableListOf<SatPass>()
val dateNow = Date()
val gsp = prefsManager.getPosition()
calculationJob = viewModelScope.launch(Dispatchers.Default) {
repository.getSelectedEntries().forEach {
passList.addAll(getPassesForEntries(it, dateNow, gsp))
}
passList = filterAndSortPasses(passList, dateNow, getHoursAhead())
_satPassList.postValue(Result.Success(passList))
}
}
fun setDefaultTleSources() {
if (prefsManager.isFirstLaunch()) {
viewModelScope.launch {
val defSourcesList = listOf(
TleSource("https://celestrak.com/NORAD/elements/active.txt"),
TleSource("https://amsat.org/tle/current/nasabare.txt")
)
repository.updateSources(defSourcesList)
}
}
}
fun getTleSources(): List<TleSource> = runBlocking {
return@runBlocking repository.getSources()
}
private fun getPassesForEntries(
entry: SatEntry,
dateNow: Date,
gsp: GroundStationPosition
): MutableList<SatPass> {
val predictor = PassPredictor(entry.tle, gsp)
val passes = predictor.getPasses(dateNow, getHoursAhead(), true)
val passList = passes.map { SatPass(entry.tle, predictor, it) }
return passList as MutableList<SatPass>
}
private fun filterAndSortPasses(
passes: MutableList<SatPass>,
dateNow: Date,
hoursAhead: Int
): MutableList<SatPass> {
val dateFuture = Calendar.getInstance().let {
it.time = dateNow
it.add(Calendar.HOUR, hoursAhead)
it.time
}
passes.removeAll { it.pass.startTime.after(dateFuture) }
passes.removeAll { it.pass.endTime.before(dateNow) }
passes.removeAll { it.pass.maxEl < getMinElevation() }
passes.sortBy { it.pass.startTime }
return passes
}
}
@@ -1,66 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.databinding.ItemSatEntryBinding
class SatEntryAdapter(private var entries: MutableList<SatEntry>) :
RecyclerView.Adapter<SatEntryAdapter.SatEntryHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SatEntryHolder {
val binding = ItemSatEntryBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return SatEntryHolder(binding.root, binding)
}
override fun onBindViewHolder(holder: SatEntryHolder, position: Int) {
holder.bind(entries[position])
}
override fun getItemCount(): Int {
return entries.size
}
fun setEntries(list: MutableList<SatEntry>) {
entries = list
notifyDataSetChanged()
}
fun getEntries(): MutableList<SatEntry> {
return entries
}
inner class SatEntryHolder(itemView: View, private val binding: ItemSatEntryBinding) :
RecyclerView.ViewHolder(itemView) {
fun bind(satEntry: SatEntry) {
binding.satEntryCheckbox.text = satEntry.name
binding.satEntryCheckbox.isChecked = satEntry.isSelected
itemView.setOnClickListener {
satEntry.isSelected = binding.satEntryCheckbox.isChecked
}
}
}
}
@@ -1,156 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.data.SatPass
import com.rtbishop.look4sat.databinding.ItemPassGeoBinding
import com.rtbishop.look4sat.databinding.ItemPassLeoBinding
import com.rtbishop.look4sat.ui.fragments.PassListFragmentDirections
import com.rtbishop.look4sat.utility.PrefsManager
import java.text.SimpleDateFormat
import java.util.*
class SatPassAdapter(
private var satPassList: MutableList<SatPass>,
private val prefsManager: PrefsManager
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
fun setList(list: MutableList<SatPass>) {
satPassList = list
notifyDataSetChanged()
}
fun updateRecycler() {
val timeNow = Date()
val iterator = satPassList.listIterator()
while (iterator.hasNext()) {
val satPass = iterator.next()
if (satPass.progress < 100) {
val timeStart = satPass.pass.startTime
val timeEnd = satPass.pass.endTime
if (timeNow.after(timeStart)) {
satPass.active = true
val index = satPassList.indexOf(satPass)
val deltaTotal = timeEnd.time.minus(timeStart.time)
val deltaNow = timeNow.time.minus(timeStart.time)
satPass.progress = ((deltaNow.toFloat() / deltaTotal.toFloat()) * 100).toInt()
notifyItemChanged(index)
}
} else {
val index = satPassList.indexOf(satPass)
iterator.remove()
notifyItemRemoved(index)
}
}
}
override fun getItemCount(): Int {
return satPassList.size
}
override fun getItemViewType(position: Int): Int {
return if (satPassList[position].tle.isDeepspace) 1
else 0
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == 0) {
val bindingLeo = ItemPassLeoBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
SatPassLeoHolder(bindingLeo.root, bindingLeo)
} else {
val bindingGeo = ItemPassGeoBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
SatPassGeoHolder(bindingGeo.root, bindingGeo)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder.itemViewType == 0) {
(holder as SatPassLeoHolder).bind(satPassList[position])
} else {
(holder as SatPassGeoHolder).bind(satPassList[position])
}
}
inner class SatPassLeoHolder(itemView: View, private val binding: ItemPassLeoBinding) :
RecyclerView.ViewHolder(itemView) {
fun bind(satPass: SatPass) {
val context: Context = itemView.context
if (satPass.active) binding.passLeoImg.setImageResource(R.drawable.ic_pass_active)
else binding.passLeoImg.setImageResource(R.drawable.ic_pass_inactive)
binding.passLeoSatName.text = satPass.tle.name
binding.passLeoSatId.text =
String.format(context.getString(R.string.pass_satId), satPass.tle.catnum)
binding.passLeoMaxEl.text =
String.format(context.getString(R.string.pat_elevation), satPass.pass.maxEl)
binding.passLeoAosAz.text =
String.format(context.getString(R.string.pass_aos_az), satPass.pass.aosAzimuth)
binding.passLeoLosAz.text =
String.format(context.getString(R.string.pass_los_az), satPass.pass.losAzimuth)
binding.passLeoProgress.progress = satPass.progress
val dateFormat =
SimpleDateFormat(context.getString(R.string.pass_dateTime), Locale.getDefault())
if (prefsManager.isTimeUTC()) dateFormat.timeZone = TimeZone.getTimeZone("UTC")
binding.passLeoAosTime.text = dateFormat.format(satPass.pass.startTime)
binding.passLeoLosTime.text = dateFormat.format(satPass.pass.endTime)
itemView.setOnClickListener {
val passIndex = satPassList.indexOf(satPass)
val action = PassListFragmentDirections.actionPassToPolar(passIndex)
itemView.findNavController().navigate(action)
}
}
}
inner class SatPassGeoHolder(itemView: View, private val binding: ItemPassGeoBinding) :
RecyclerView.ViewHolder(itemView) {
fun bind(satPass: SatPass) {
val context: Context = itemView.context
val satPos = satPass.predictor.getSatPos(satPass.pass.startTime)
val azimuth = satPos.azimuth * 180 / Math.PI
binding.passGeoName.text = satPass.tle.name
binding.passGeoId.text =
String.format(context.getString(R.string.pass_satId), satPass.tle.catnum)
binding.passGeoAz.text = String.format(context.getString(R.string.pat_azimuth), azimuth)
binding.passGeoEl.text =
String.format(context.getString(R.string.pat_elevation), satPass.pass.maxEl)
itemView.setOnClickListener {
val passIndex = satPassList.indexOf(satPass)
val action = PassListFragmentDirections.actionPassToPolar(passIndex)
itemView.findNavController().navigate(action)
}
}
}
}
@@ -1,91 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.adapters
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.databinding.ItemTleSourceBinding
class TleSourcesAdapter(private var sources: MutableList<TleSource>) :
RecyclerView.Adapter<TleSourcesAdapter.TleSourceHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TleSourceHolder {
val binding = ItemTleSourceBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return TleSourceHolder(binding.root, binding, TleSourceWatcher())
}
override fun onBindViewHolder(holder: TleSourceHolder, position: Int) {
holder.textWatcher.updatePosition(position)
holder.bind(sources[position])
}
override fun getItemCount(): Int {
return sources.size
}
fun getSources(): MutableList<TleSource> {
return sources
}
fun setSources(list: MutableList<TleSource>) {
sources = list
notifyDataSetChanged()
}
inner class TleSourceHolder(
itemView: View,
val binding: ItemTleSourceBinding,
val textWatcher: TleSourceWatcher
) :
RecyclerView.ViewHolder(itemView) {
fun bind(source: TleSource) {
binding.tleSourceUrl.setText(source.url)
binding.tleSourceUrl.addTextChangedListener(textWatcher)
binding.tleSourceBtnDel.setOnClickListener {
sources.remove(source)
notifyItemRemoved(adapterPosition)
}
}
}
inner class TleSourceWatcher : TextWatcher {
private var position = 0
fun updatePosition(position: Int) {
this.position = position
}
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
sources[position].url = s.toString()
}
}
}
@@ -1,142 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.data.Transmitter
import com.rtbishop.look4sat.databinding.ItemTransmitterBinding
import com.rtbishop.look4sat.utility.PassPredictor
import java.util.*
class TransmitterAdapter : RecyclerView.Adapter<TransmitterAdapter.TransmitterHolder>() {
private var transmittersList = emptyList<Transmitter>()
private lateinit var predictor: PassPredictor
fun setPredictor(predict: PassPredictor) {
predictor = predict
}
fun setList(list: List<Transmitter>) {
transmittersList = list
}
override fun getItemCount(): Int {
return transmittersList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TransmitterHolder {
val binding = ItemTransmitterBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return TransmitterHolder(binding.root, binding)
}
override fun onBindViewHolder(holder: TransmitterHolder, position: Int) {
holder.bind(transmittersList[position])
}
inner class TransmitterHolder(itemView: View, private val binding: ItemTransmitterBinding) :
RecyclerView.ViewHolder(itemView) {
fun bind(transmitter: Transmitter) {
val context: Context = itemView.context
val freqDivider = 1000000f
binding.transDescription.text = transmitter.description
if (transmitter.downlinkLow != null && transmitter.downlinkHigh == null) {
binding.transDownlink.text = String
.format(
context.getString(R.string.trans_down_low),
transmitter.downlinkLow / freqDivider
)
binding.transDownlinkDoppler.text = String
.format(
context.getString(R.string.trans_down_low_doppler),
predictor.getDownlinkFreq(transmitter.downlinkLow, Date()) / freqDivider
)
} else if (transmitter.downlinkLow != null && transmitter.downlinkHigh != null) {
binding.transDownlink.text = String
.format(
context.getString(R.string.trans_down_lowHigh),
transmitter.downlinkLow / freqDivider,
transmitter.downlinkHigh / freqDivider
)
binding.transDownlinkDoppler.text = String
.format(
context.getString(R.string.trans_down_lowHigh_doppler),
predictor.getDownlinkFreq(transmitter.downlinkLow, Date()) / freqDivider,
predictor.getDownlinkFreq(transmitter.downlinkHigh, Date()) / freqDivider
)
} else {
binding.transDownlink.text = context.getString(R.string.no_downlink)
binding.transDownlinkDoppler.text = context.getString(R.string.no_downlink_doppler)
}
if (transmitter.uplinkLow != null && transmitter.uplinkHigh == null) {
binding.transUplink.text = String.format(
context.getString(R.string.trans_up_low),
transmitter.uplinkLow / freqDivider
)
binding.transUplinkDoppler.text = String.format(
context.getString(R.string.trans_up_low_doppler),
predictor.getUplinkFreq(transmitter.uplinkLow, Date()) / freqDivider
)
} else if (transmitter.uplinkLow != null && transmitter.uplinkHigh != null) {
binding.transUplink.text = String.format(
context.getString(R.string.trans_up_lowHigh),
transmitter.uplinkLow / freqDivider,
transmitter.uplinkHigh / freqDivider
)
binding.transUplinkDoppler.text = String.format(
context.getString(R.string.trans_up_lowHigh_doppler),
predictor.getUplinkFreq(transmitter.uplinkLow, Date()) / freqDivider,
predictor.getUplinkFreq(transmitter.uplinkHigh, Date()) / freqDivider
)
} else {
binding.transUplink.text = context.getString(R.string.no_uplink)
binding.transUplinkDoppler.text = context.getString(R.string.no_uplink_doppler)
}
if (transmitter.mode != null) {
binding.transMode.text =
String.format(context.getString(R.string.trans_mode), transmitter.mode)
} else {
binding.transMode.text = context.getString(R.string.no_mode)
}
if (transmitter.isInverted) {
binding.transInverted.text = String.format(
context.getString(R.string.trans_inverted),
context.getString(R.string.btn_yes)
)
} else {
binding.transInverted.text = String.format(
context.getString(R.string.trans_inverted),
context.getString(R.string.btn_no)
)
}
}
}
}
@@ -1,39 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import androidx.fragment.app.Fragment
import com.rtbishop.look4sat.BuildConfig
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.databinding.FragmentAboutBinding
class AboutFragment : Fragment(R.layout.fragment_about) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentAboutBinding.bind(view)
binding.tvAboutVersion.text =
String.format(getString(R.string.app_version), BuildConfig.VERSION_NAME)
binding.tvAboutMessage.movementMethod = LinkMovementMethod.getInstance()
}
}
@@ -1,339 +0,0 @@
package com.rtbishop.look4sat.ui.fragments
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import com.github.amsacode.predict4java.GroundStationPosition
import com.rtbishop.look4sat.Look4SatApp
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.dagger.ViewModelFactory
import com.rtbishop.look4sat.data.Result
import com.rtbishop.look4sat.data.SatItem
import com.rtbishop.look4sat.data.SatPass
import com.rtbishop.look4sat.databinding.FragmentMapOsmBinding
import com.rtbishop.look4sat.ui.MainActivity
import com.rtbishop.look4sat.ui.SharedViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.osmdroid.config.Configuration
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase
import org.osmdroid.tileprovider.tilesource.TileSourcePolicy
import org.osmdroid.tileprovider.tilesource.XYTileSource
import org.osmdroid.util.BoundingBox
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.overlay.*
import java.util.*
import javax.inject.Inject
import kotlin.math.pow
import kotlin.math.sqrt
class MapOsmFragment : Fragment(R.layout.fragment_map_osm) {
@Inject
lateinit var modelFactory: ViewModelFactory
private lateinit var mainActivity: MainActivity
private lateinit var viewModel: SharedViewModel
private lateinit var binding: FragmentMapOsmBinding
private lateinit var trackPaint: Paint
private lateinit var footprintPaint: Paint
private lateinit var selectedPass: SatPass
private val dateNow = Date(System.currentTimeMillis())
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentMapOsmBinding.bind(view)
mainActivity = requireActivity() as MainActivity
(mainActivity.application as Look4SatApp).appComponent.inject(this)
viewModel = ViewModelProvider(mainActivity, modelFactory).get(SharedViewModel::class.java)
val prefs = PreferenceManager.getDefaultSharedPreferences(mainActivity.applicationContext)
Configuration.getInstance().load(mainActivity.applicationContext, prefs)
trackPaint = Paint().apply {
strokeWidth = 2f
style = Paint.Style.STROKE
color = ContextCompat.getColor(mainActivity, R.color.satTrack)
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
isAntiAlias = true
}
footprintPaint = Paint().apply {
style = Paint.Style.FILL_AND_STROKE
color = ContextCompat.getColor(mainActivity, R.color.satOsmTemp)
isAntiAlias = true
}
setupMapView()
setupObservers()
}
private fun setupMapView() {
binding.mapView.apply {
setMultiTouchControls(true)
setTileSource(getWikimediaTileSource())
minZoomLevel = 2.5
maxZoomLevel = 6.0
controller.setZoom(minZoomLevel)
zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
isHorizontalMapRepetitionEnabled = false
isVerticalMapRepetitionEnabled = false
overlayManager.tilesOverlay.loadingBackgroundColor = Color.TRANSPARENT
overlayManager.tilesOverlay.loadingLineColor = Color.TRANSPARENT
setScrollableAreaLimitDouble(BoundingBox(85.05, 180.0, -85.05, -180.0))
// apply filter
val tilesFilter = getColorFilter(Color.parseColor("#D50000"))
overlayManager.tilesOverlay.setColorFilter(tilesFilter)
// add overlays: 0 - GSP, 1 - SatTrack, 2 - SatFootprint, 3 - SatIcons
val layers = listOf(FolderOverlay(), FolderOverlay(), FolderOverlay(), FolderOverlay())
overlays.addAll(layers)
}
}
private fun getWikimediaTileSource(): OnlineTileSourceBase {
return XYTileSource(
"wikimedia",
2,
6,
256,
".png",
arrayOf("https://maps.wikimedia.org/osm-intl/"),
resources.getString(R.string.osmCopyright),
TileSourcePolicy(
1, TileSourcePolicy.FLAG_NO_BULK and TileSourcePolicy.FLAG_NO_PREVENTIVE and
TileSourcePolicy.FLAG_USER_AGENT_MEANINGFUL and TileSourcePolicy.FLAG_USER_AGENT_NORMALIZED
)
)
}
private fun setupObservers() {
viewModel.getGSP().observe(viewLifecycleOwner, { stationPosition ->
when (stationPosition) {
is Result.Success -> {
setupPosOverlay(stationPosition.data)
}
}
})
viewModel.getPassList().observe(viewLifecycleOwner, { satPasses ->
when (satPasses) {
is Result.Success -> {
if (satPasses.data.isNotEmpty()) {
val filteredPasses = satPasses.data.distinctBy { it.tle }
selectedPass = filteredPasses[0]
setupSatOverlay(filteredPasses)
}
}
}
})
}
private fun setupPosOverlay(gsp: GroundStationPosition) {
Marker(binding.mapView).apply {
setInfoWindow(null)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_map_pos, mainActivity.theme)
position = GeoPoint(gsp.latitude, gsp.longitude)
binding.mapView.overlays[0] = this
binding.mapView.invalidate()
}
}
private fun setupSatOverlay(passList: List<SatPass>) {
lifecycleScope.launch {
while (true) {
dateNow.time = System.currentTimeMillis()
binding.mapView.overlays[3] = getSatIcons(passList)
binding.mapView.overlays[2] = getSatFootprint(selectedPass)
setSatInfo(selectedPass)
binding.mapView.invalidate()
delay(3000)
}
}
}
private suspend fun getSatIcons(passList: List<SatPass>): Overlay =
withContext(Dispatchers.Default) {
val icon =
ResourcesCompat.getDrawable(resources, R.drawable.ic_map_sat, mainActivity.theme)
val items = mutableListOf<SatItem>()
passList.forEach {
val satPos = it.predictor.getSatPos(dateNow)
var lat = Math.toDegrees(satPos.latitude)
var lon = Math.toDegrees(satPos.longitude)
if (lat > 85.05) lat = 85.05
else if (lat < -85.05) lat = -85.05
if (lon > 180.0) lon -= 360.0
SatItem(it.tle.name, it.tle.name, GeoPoint(lat, lon), it).apply {
markerHotspot = OverlayItem.HotspotPlace.CENTER
items.add(this)
}
}
val listener = object : ItemizedIconOverlay.OnItemGestureListener<SatItem> {
override fun onItemLongPress(index: Int, item: SatItem): Boolean {
return true
}
override fun onItemSingleTapUp(index: Int, item: SatItem): Boolean {
selectedPass = item.pass
setSatDetails(item.pass)
return true
}
}
return@withContext ItemizedIconOverlay(items, icon, listener, mainActivity)
}
private fun setSatDetails(satPass: SatPass) {
setSatInfo(satPass)
binding.mapView.overlays[1] = getSatTrack(satPass)
binding.mapView.overlays[2] = getSatFootprint(satPass)
binding.mapView.invalidate()
}
private fun setSatInfo(satPass: SatPass) {
val satPos = satPass.predictor.getSatPos(dateNow)
val satLat = Math.toDegrees(satPos.latitude).toFloat()
var satLon = Math.toDegrees(satPos.longitude).toFloat()
if (satLon > 180f) satLon -= 360f
binding.idName.text =
String.format(
mainActivity.getString(R.string.pat_osm_idName),
satPass.tle.catnum,
satPass.tle.name
)
binding.altitude.text =
String.format(mainActivity.getString(R.string.pat_altitude), satPos.altitude)
binding.distance.text =
String.format(mainActivity.getString(R.string.pat_distance), satPos.range)
binding.velocity.text =
String.format(
mainActivity.getString(R.string.pat_osm_vel),
getSatVelocity(satPos.altitude)
)
binding.latLon.text =
String.format(mainActivity.getString(R.string.pat_osm_latLon), satLat, satLon)
}
private fun getSatVelocity(satAlt: Double): Double {
val earthG = 6.674 * 10.0.pow(-11)
val earthM = 5.98 * 10.0.pow(24)
val radius = 6.37 * 10.0.pow(6) + satAlt * 10.0.pow(3)
return sqrt(earthG * earthM / radius) / 1000
}
private fun getSatTrack(pass: SatPass): Overlay {
val period = (24 * 60 / pass.tle.meanmo).toInt()
val positions = pass.predictor.getPositions(dateNow, 20, 0, period * 3)
val trackOverlay = FolderOverlay()
val trackPoints = mutableListOf<GeoPoint>()
var oldLon = 0.0
positions.forEach {
val newLat = Math.toDegrees(it.latitude)
var newLon = Math.toDegrees(it.longitude)
if (newLon > 180.0) newLon -= 360.0
if (oldLon < -170.0 && newLon > 170.0 || oldLon > 170.0 && newLon < -170.0) {
val currentPoints = mutableListOf<GeoPoint>()
currentPoints.addAll(trackPoints)
Polyline().apply {
outlinePaint.set(trackPaint)
setPoints(currentPoints)
trackOverlay.add(this)
}
trackPoints.clear()
}
oldLon = newLon
trackPoints.add(GeoPoint(newLat, newLon))
}
Polyline().apply {
outlinePaint.set(trackPaint)
setPoints(trackPoints)
trackOverlay.add(this)
}
return trackOverlay
}
private fun getSatFootprint(pass: SatPass): Overlay {
val rangeCircle = pass.predictor.getSatPos(dateNow).rangeCircle
val rangePoints = mutableListOf<GeoPoint>()
var zeroPoint = GeoPoint(0.0, 0.0)
rangeCircle.withIndex().forEach {
var lat = it.value.lat
var lon = it.value.lon
if (lat > 85.05) lat = 85.05
else if (lat < -85.05) lat = -85.05
if (lon > 180.0) lon -= 360.0
if (it.index == 0) zeroPoint = GeoPoint(lat, lon)
rangePoints.add(GeoPoint(lat, lon))
}
rangePoints.add(zeroPoint)
return Polygon().apply {
fillPaint.set(footprintPaint)
outlinePaint.set(footprintPaint)
points = rangePoints
}
}
private fun getColorFilter(targetColor: Int): ColorMatrixColorFilter {
val newR = Color.red(targetColor) / 255f
val newG = Color.green(targetColor) / 255f
val newB = Color.blue(targetColor) / 255f
val negativeMatrix = ColorMatrix(
floatArrayOf(
-1f, 0f, 0f, 0f, 255f,
0f, -1f, 0f, 0f, 255f,
0f, 0f, -1f, 0f, 255f,
0f, 0f, 0f, 1f, 0f
)
)
val tintedMatrix = ColorMatrix(
floatArrayOf(
newR, newG, newB, 0f, 0f,
newR, newG, newB, 0f, 0f,
newR, newG, newB, 0f, 0f,
0f, 0f, 0f, 0f, 255f
)
)
tintedMatrix.preConcat(negativeMatrix)
return ColorMatrixColorFilter(tintedMatrix)
}
override fun onPause() {
binding.mapView.onPause()
super.onPause()
}
override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
}
@@ -1,149 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.github.amsacode.predict4java.GroundStationPosition
import com.github.amsacode.predict4java.TLE
import com.rtbishop.look4sat.Look4SatApp
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.dagger.ViewModelFactory
import com.rtbishop.look4sat.data.Result
import com.rtbishop.look4sat.data.SatPass
import com.rtbishop.look4sat.databinding.FragmentMapViewBinding
import com.rtbishop.look4sat.ui.MainActivity
import com.rtbishop.look4sat.ui.SharedViewModel
import com.rtbishop.look4sat.ui.views.MapView
import com.rtbishop.look4sat.utility.Extensions.toast
import com.rtbishop.look4sat.utility.PassPredictor
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject
class MapViewFragment : Fragment(R.layout.fragment_map_view) {
@Inject
lateinit var modelFactory: ViewModelFactory
private lateinit var mainActivity: MainActivity
private lateinit var viewModel: SharedViewModel
private lateinit var mapView: MapView
private lateinit var predictor: PassPredictor
private lateinit var selectedSat: TLE
private lateinit var binding: FragmentMapViewBinding
private var gsp = GroundStationPosition(0.0, 0.0, 0.0)
private var satPassList = emptyList<SatPass>()
private var checkedItem = 0
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentMapViewBinding.bind(view)
mainActivity = requireActivity() as MainActivity
(mainActivity.application as Look4SatApp).appComponent.inject(this)
viewModel = ViewModelProvider(mainActivity, modelFactory).get(SharedViewModel::class.java)
setupObservers(binding)
}
private fun setupObservers(binding: FragmentMapViewBinding) {
viewModel.getGSP().observe(viewLifecycleOwner, { result ->
when (result) {
is Result.Success -> gsp = result.data
}
})
viewModel.getPassList().observe(viewLifecycleOwner, { result ->
when (result) {
is Result.Success -> {
satPassList = result.data
setupMapView(binding)
}
}
})
}
private fun setupMapView(binding: FragmentMapViewBinding) {
if (satPassList.isNotEmpty()) {
satPassList = satPassList.distinctBy { it.tle }
satPassList = satPassList.sortedBy { it.tle.name }
binding.fabMap.setOnClickListener { showSelectSatDialog(satPassList) }
selectedSat = satPassList.first().tle
predictor = satPassList.first().predictor
mapView = MapView(mainActivity, gsp)
mapView.setList(satPassList)
mapView.setChecked(checkedItem)
binding.frameMap.addView(mapView)
refreshView()
} else {
binding.fabMap.setOnClickListener {
getString(R.string.err_no_sat_selected).toast(mainActivity)
}
}
}
private fun refreshView() {
lifecycleScope.launch {
while (true) {
mapView.invalidate()
setDataToTextViews()
delay(viewModel.getRefreshRate())
}
}
}
private fun showSelectSatDialog(list: List<SatPass>) {
val tleArray = arrayOfNulls<String>(list.size).apply {
list.withIndex().forEach {
this[it.index] = it.value.tle.name
}
}
val builder = AlertDialog.Builder(mainActivity)
builder.setTitle(getString(R.string.dialog_show_track))
.setSingleChoiceItems(tleArray, checkedItem) { dialog, which ->
checkedItem = which
selectedSat = list[which].tle
predictor = list[which].predictor
mapView.setChecked(checkedItem)
mapView.invalidate()
dialog.dismiss()
}
.create()
.show()
}
private fun setDataToTextViews() {
val currentTime = Date(System.currentTimeMillis())
val position = predictor.getSatPos(currentTime)
var lon = Math.toDegrees(position.longitude).toFloat()
val lat = Math.toDegrees(position.latitude).toFloat()
val rng = position.range
if (lon > 180f) lon -= 360f
binding.tvMapLat.text = String.format(mainActivity.getString(R.string.pat_latitude), lat)
binding.tvMapLon.text = String.format(mainActivity.getString(R.string.pat_longitude), lon)
binding.tvMapRng.text = String.format(mainActivity.getString(R.string.pat_distance), rng)
}
}
@@ -1,281 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.rtbishop.look4sat.Look4SatApp
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.dagger.ViewModelFactory
import com.rtbishop.look4sat.data.Result
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.data.SatPass
import com.rtbishop.look4sat.databinding.FragmentPassListBinding
import com.rtbishop.look4sat.ui.MainActivity
import com.rtbishop.look4sat.ui.SharedViewModel
import com.rtbishop.look4sat.ui.adapters.SatPassAdapter
import com.rtbishop.look4sat.utility.Extensions.toast
import com.rtbishop.look4sat.utility.PrefsManager
import kotlinx.coroutines.launch
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class PassListFragment : Fragment(R.layout.fragment_pass_list) {
@Inject
lateinit var modelFactory: ViewModelFactory
@Inject
lateinit var prefsManager: PrefsManager
private lateinit var viewModel: SharedViewModel
private lateinit var satPassAdapter: SatPassAdapter
private lateinit var btnPassPrefs: ImageButton
private lateinit var aosTimer: CountDownTimer
private lateinit var aosTimerText: TextView
private lateinit var mainActivity: MainActivity
private var isTimerSet: Boolean = false
private var satPassList: MutableList<SatPass> = mutableListOf()
private var _binding: FragmentPassListBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentPassListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainActivity = activity as MainActivity
(mainActivity.application as Look4SatApp).appComponent.inject(this)
viewModel = ViewModelProvider(mainActivity, modelFactory).get(SharedViewModel::class.java)
satPassAdapter = SatPassAdapter(satPassList, prefsManager)
aosTimerText = mainActivity.findViewById(R.id.toolbar_timer)
btnPassPrefs = mainActivity.findViewById(R.id.toolbar_filter)
setupObservers(binding)
setupComponents(binding)
}
override fun onStart() {
super.onStart()
if (satPassAdapter.itemCount == 0) {
viewModel.calculatePasses()
}
}
private fun setupObservers(binding: FragmentPassListBinding) {
viewModel.getPassList().observe(viewLifecycleOwner, { result ->
when (result) {
is Result.Success -> {
satPassList = result.data
satPassAdapter.setList(satPassList)
if (satPassList.isNotEmpty()) {
binding.layoutInfo.visibility = View.INVISIBLE
binding.recPassList.visibility = View.VISIBLE
} else {
binding.layoutInfo.visibility = View.VISIBLE
binding.recPassList.visibility = View.INVISIBLE
}
setTimer()
binding.refLayoutPassList.isRefreshing = false
}
is Result.InProgress -> {
binding.refLayoutPassList.isRefreshing = true
}
}
})
}
private fun setupComponents(binding: FragmentPassListBinding) {
binding.recPassList.apply {
layoutManager = LinearLayoutManager(mainActivity)
adapter = satPassAdapter
isVerticalScrollBarEnabled = false
(itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
}
satPassAdapter.setList(satPassList)
setTimer()
binding.refLayoutPassList.setProgressBackgroundColorSchemeResource(R.color.themeAccent)
binding.refLayoutPassList.setColorSchemeResources(R.color.backgroundDark)
binding.refLayoutPassList.setOnRefreshListener { viewModel.calculatePasses() }
btnPassPrefs.setOnClickListener {
showSatPassPrefsDialog(viewModel.getHoursAhead(), viewModel.getMinElevation())
}
binding.fabSatSelect.setOnClickListener {
lifecycleScope.launch {
val list = viewModel.getAllEntries() as MutableList
if (list.isEmpty()) {
getString(R.string.err_update_data).toast(mainActivity, Toast.LENGTH_SHORT)
} else {
showSelectSatDialog(list)
}
}
}
}
private fun showSatPassPrefsDialog(hoursAhead: Int, minEl: Double) {
val satPassPrefView = View.inflate(mainActivity, R.layout.dialog_pass_pref, null)
val etHoursAhead = satPassPrefView.findViewById<EditText>(R.id.pref_et_hoursAhead)
val etMinEl = satPassPrefView.findViewById<EditText>(R.id.pref_et_minEl)
etHoursAhead.setText(hoursAhead.toString())
etMinEl.setText(minEl.toString())
AlertDialog.Builder(mainActivity).apply {
setPositiveButton(getString(android.R.string.ok)) { _, _ ->
val hoursStr = etHoursAhead.text.toString()
val elevationStr = etMinEl.text.toString()
if (hoursStr.isNotEmpty() && elevationStr.isNotEmpty()) {
val hours = hoursStr.toInt()
val elevation = elevationStr.toDouble()
when {
hours < 1 || hours > 168 -> {
getString(R.string.pref_hours_ahead_input_error).toast(
mainActivity,
Toast.LENGTH_SHORT
)
}
elevation < 0 || elevation > 90 -> {
getString(R.string.pref_min_el_input_error).toast(
mainActivity,
Toast.LENGTH_SHORT
)
}
else -> {
viewModel.setPassPrefs(hours, elevation)
viewModel.calculatePasses()
}
}
} else getString(R.string.err_enter_value).toast(mainActivity, Toast.LENGTH_SHORT)
}
setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
dialog.cancel()
}
setView(satPassPrefView)
create()
show()
}
}
private fun showSelectSatDialog(tleMainList: MutableList<SatEntry>) {
val listener = object : SatEntryDialogFragment.EntriesSubmitListener {
override fun onEntriesSubmit(catNumList: MutableList<Int>) {
viewModel.updateEntriesSelection(catNumList)
}
}
SatEntryDialogFragment(tleMainList).apply {
setEntriesListener(listener)
show(mainActivity.supportFragmentManager, "SatEntryDialogFragment")
}
}
private fun setTimer() {
if (satPassList.isNotEmpty()) {
resetTimer()
val timeNow = Date()
try {
setTimerForNext(timeNow)
} catch (e: NoSuchElementException) {
setTimerForLast(timeNow)
} finally {
aosTimer.start()
isTimerSet = true
}
} else {
resetTimer(true)
}
}
private fun setTimerForNext(timeNow: Date) {
val nextPass = satPassList.first { it.pass.startTime.after(timeNow) }
val millisBeforeStart = nextPass.pass.startTime.time.minus(timeNow.time)
aosTimer = object : CountDownTimer(millisBeforeStart, 1000) {
override fun onFinish() {
setTimer()
}
override fun onTick(millisUntilFinished: Long) {
aosTimerText.text = String.format(
mainActivity.getString(R.string.pat_timer),
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60
)
satPassAdapter.updateRecycler()
}
}
}
private fun setTimerForLast(timeNow: Date) {
val lastPass = satPassList.last()
val millisBeforeEnd = lastPass.pass.endTime.time.minus(timeNow.time)
aosTimer = object : CountDownTimer(millisBeforeEnd, 1000) {
override fun onFinish() {
viewModel.calculatePasses()
}
override fun onTick(millisUntilFinished: Long) {
aosTimerText.text = String.format(
mainActivity.getString(R.string.pat_timer),
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60
)
satPassAdapter.updateRecycler()
}
}
}
private fun resetTimer(resetToNull: Boolean = false) {
if (isTimerSet) {
aosTimer.cancel()
isTimerSet = false
}
if (resetToNull) aosTimerText.text =
String.format(getString(R.string.pat_timer), 0, 0, 0)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
@@ -1,173 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.content.Context
import android.hardware.*
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.rtbishop.look4sat.Look4SatApp
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.dagger.ViewModelFactory
import com.rtbishop.look4sat.data.Result
import com.rtbishop.look4sat.data.SatPass
import com.rtbishop.look4sat.databinding.FragmentPolarViewBinding
import com.rtbishop.look4sat.ui.MainActivity
import com.rtbishop.look4sat.ui.SharedViewModel
import com.rtbishop.look4sat.ui.adapters.TransmitterAdapter
import com.rtbishop.look4sat.ui.views.PolarView
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject
import kotlin.math.round
class PolarViewFragment : Fragment(R.layout.fragment_polar_view), SensorEventListener {
@Inject
lateinit var modelFactory: ViewModelFactory
private lateinit var mainActivity: MainActivity
private lateinit var viewModel: SharedViewModel
private lateinit var binding: FragmentPolarViewBinding
private lateinit var satPass: SatPass
private lateinit var sensorManager: SensorManager
private var polarView: PolarView? = null
private val args: PolarViewFragmentArgs by navArgs()
private val transmitterAdapter = TransmitterAdapter()
private var magneticDeclination = 0f
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainActivity = activity as MainActivity
binding = FragmentPolarViewBinding.bind(view)
(mainActivity.application as Look4SatApp).appComponent.inject(this)
viewModel = ViewModelProvider(mainActivity, modelFactory).get(SharedViewModel::class.java)
sensorManager = mainActivity.getSystemService(Context.SENSOR_SERVICE) as SensorManager
binding.recPolar.apply {
layoutManager = LinearLayoutManager(mainActivity)
adapter = transmitterAdapter
}
observePasses()
observeStationPosition()
}
override fun onResume() {
super.onResume()
if (viewModel.getCompass()) {
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR).also { sensor ->
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)
}
}
}
override fun onPause() {
super.onPause()
if (viewModel.getCompass()) {
sensorManager.unregisterListener(this)
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
override fun onSensorChanged(event: SensorEvent?) {
event?.let { calculateAzimuth(it) }
}
private fun calculateAzimuth(event: SensorEvent) {
val rotationValues = FloatArray(9)
SensorManager.getRotationMatrixFromVector(rotationValues, event.values)
val orientationValues = FloatArray(3)
SensorManager.getOrientation(rotationValues, orientationValues)
val magneticAzimuth = ((orientationValues[0] * 57.2957795f) + 360f) % 360f
val roundedAzimuth = round(magneticAzimuth * 100) / 100
polarView?.rotation = -(roundedAzimuth + magneticDeclination)
}
private fun observePasses() {
viewModel.getPassList().observe(viewLifecycleOwner, { result ->
if (result is Result.Success) {
val refreshRate = viewModel.getRefreshRate()
satPass = result.data[args.satPassIndex]
mainActivity.supportActionBar?.title = satPass.tle.name
polarView = PolarView(mainActivity, satPass)
binding.framePolar.addView(polarView)
observeTransmitters()
refreshText(refreshRate)
}
})
}
private fun observeTransmitters() {
viewModel.getTransmittersForSat(satPass.tle.catnum).observe(viewLifecycleOwner, {
if (it.isNotEmpty()) {
transmitterAdapter.setPredictor(satPass.predictor)
transmitterAdapter.setList(it)
transmitterAdapter.notifyDataSetChanged()
binding.recPolar.visibility = View.VISIBLE
binding.tvPolarNoTrans.visibility = View.INVISIBLE
} else {
binding.recPolar.visibility = View.INVISIBLE
binding.tvPolarNoTrans.visibility = View.VISIBLE
}
})
}
private fun observeStationPosition() {
viewModel.getGSP().observe(viewLifecycleOwner, { result ->
if (result is Result.Success) {
val geoField = GeomagneticField(
result.data.latitude.toFloat(),
result.data.longitude.toFloat(),
result.data.heightAMSL.toFloat(),
System.currentTimeMillis()
)
magneticDeclination = geoField.declination
}
})
}
private fun refreshText(rate: Long) {
lifecycleScope.launch {
while (true) {
setPassText()
polarView?.invalidate()
transmitterAdapter.notifyDataSetChanged()
delay(rate)
}
}
}
private fun setPassText() {
val satPos = satPass.predictor.getSatPos(Date())
val polarAz = mainActivity.getString(R.string.pat_azimuth)
val polarEl = mainActivity.getString(R.string.pat_elevation)
val polarRng = mainActivity.getString(R.string.pat_distance)
val polarAlt = mainActivity.getString(R.string.pat_altitude)
binding.tvPolarAz.text = String.format(polarAz, Math.toDegrees(satPos.azimuth))
binding.tvPolarEl.text = String.format(polarEl, Math.toDegrees(satPos.elevation))
binding.tvPolarRng.text = String.format(polarRng, satPos.range)
binding.tvPolarAlt.text = String.format(polarAlt, satPos.altitude)
}
}
@@ -1,133 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.content.SharedPreferences
import android.os.Bundle
import android.text.InputType
import androidx.lifecycle.ViewModelProvider
import androidx.preference.EditTextPreference
import androidx.preference.PreferenceFragmentCompat
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.ui.MainActivity
import com.rtbishop.look4sat.ui.SharedViewModel
import com.rtbishop.look4sat.utility.Extensions.toast
class PreferencesFragment : PreferenceFragmentCompat(),
SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var mainActivity: MainActivity
private lateinit var viewModel: SharedViewModel
private lateinit var keyLat: String
private lateinit var keyLon: String
private lateinit var keyAlt: String
private lateinit var keyDelay: String
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preference, rootKey)
val provider = EditTextPreference.SimpleSummaryProvider.getInstance()
mainActivity = activity as MainActivity
viewModel = ViewModelProvider(mainActivity).get(SharedViewModel::class.java)
keyLat = mainActivity.getString(R.string.pref_lat_key)
keyLon = mainActivity.getString(R.string.pref_lon_key)
keyAlt = mainActivity.getString(R.string.pref_alt_key)
keyDelay = mainActivity.getString(R.string.pref_refresh_rate_key)
findPreference<EditTextPreference>(keyLat)?.apply {
summaryProvider = provider
setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER or
InputType.TYPE_NUMBER_FLAG_DECIMAL or
InputType.TYPE_NUMBER_FLAG_SIGNED
}
setOnPreferenceChangeListener { _, newValue ->
val valueStr = newValue.toString()
if (valueStr.isEmpty() || valueStr == "-" || valueStr.toDouble() < -90.0 || valueStr.toDouble() > 90.0) {
getString(R.string.pref_lat_input_error).toast(mainActivity)
return@setOnPreferenceChangeListener false
}
return@setOnPreferenceChangeListener true
}
}
findPreference<EditTextPreference>(keyLon)?.apply {
summaryProvider = provider
setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER or
InputType.TYPE_NUMBER_FLAG_DECIMAL or
InputType.TYPE_NUMBER_FLAG_SIGNED
}
setOnPreferenceChangeListener { _, newValue ->
val valueStr = newValue.toString()
if (valueStr.isEmpty() || valueStr == "-" || valueStr.toDouble() < -180.0 || valueStr.toDouble() > 180.0) {
getString(R.string.pref_lon_input_error).toast(mainActivity)
return@setOnPreferenceChangeListener false
}
return@setOnPreferenceChangeListener true
}
}
findPreference<EditTextPreference>(keyAlt)?.apply {
summaryProvider = provider
setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER or
InputType.TYPE_NUMBER_FLAG_DECIMAL or
InputType.TYPE_NUMBER_FLAG_SIGNED
}
setOnPreferenceChangeListener { _, newValue ->
val valueStr = newValue.toString()
if (valueStr.isEmpty() || valueStr == "-" || valueStr.toDouble() < -413.0 || valueStr.toDouble() > 8850.0) {
getString(R.string.pref_alt_input_error).toast(mainActivity)
return@setOnPreferenceChangeListener false
}
return@setOnPreferenceChangeListener true
}
}
findPreference<EditTextPreference>(keyDelay)?.apply {
summaryProvider = provider
setOnBindEditTextListener { it.inputType = InputType.TYPE_CLASS_NUMBER }
setOnPreferenceChangeListener { _, newValue ->
val valueStr = newValue.toString()
if (valueStr.isEmpty() || valueStr.toLong() < 250 || valueStr.toLong() > 10000) {
getString(R.string.pref_refresh_rate_input_error).toast(mainActivity)
return@setOnPreferenceChangeListener false
}
return@setOnPreferenceChangeListener true
}
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == keyLat || key == keyLon || key == keyAlt) viewModel.setPositionFromPref()
}
override fun onResume() {
super.onResume()
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
}
@@ -1,138 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.app.Dialog
import android.os.Bundle
import android.view.ViewGroup
import android.view.Window
import android.widget.SearchView
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.rtbishop.look4sat.data.SatEntry
import com.rtbishop.look4sat.databinding.DialogSatEntryBinding
import com.rtbishop.look4sat.ui.adapters.SatEntryAdapter
import java.util.*
class SatEntryDialogFragment(private var entries: MutableList<SatEntry>) :
AppCompatDialogFragment(), SearchView.OnQueryTextListener {
private lateinit var entriesListener: EntriesSubmitListener
private val entryAdapter = SatEntryAdapter(entries)
private var selectAllToggle = true
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogSatEntryBinding.inflate(requireActivity().layoutInflater)
val satEntryDialog = Dialog(requireActivity()).apply {
window?.requestFeature(Window.FEATURE_NO_TITLE)
setContentView(binding.root)
window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
binding.dialogSearch.apply {
setOnQueryTextListener(this@SatEntryDialogFragment)
onActionViewExpanded()
clearFocus()
}
binding.dialogRecycler.apply {
layoutManager = LinearLayoutManager(activity)
adapter = entryAdapter
}
binding.dialogBtnPositive.setOnClickListener { onPositiveClicked() }
binding.dialogBtnNegative.setOnClickListener { onNegativeClicked() }
binding.dialogBtnNeutral.setOnClickListener { onNeutralClicked() }
return satEntryDialog
}
fun setEntriesListener(listener: EntriesSubmitListener): SatEntryDialogFragment {
entriesListener = listener
return this
}
private fun filterEntries(list: MutableList<SatEntry>, query: String): MutableList<SatEntry> {
if (query.isEmpty()) return list
return try {
filterByCatNum(list, query.toInt())
} catch (e: NumberFormatException) {
filterByName(list, query)
}
}
private fun filterByCatNum(list: MutableList<SatEntry>, catNum: Int): MutableList<SatEntry> {
val filteredList = list.filter { it.catNum == catNum }
return filteredList as MutableList<SatEntry>
}
private fun filterByName(list: MutableList<SatEntry>, query: String): MutableList<SatEntry> {
val searchQuery = query.toLowerCase(Locale.getDefault())
val filteredList = mutableListOf<SatEntry>()
list.forEach {
val name = it.name.toLowerCase(Locale.getDefault())
if (name.contains(searchQuery)) filteredList.add(it)
}
return filteredList
}
private fun onPositiveClicked() {
val catNumList = mutableListOf<Int>().apply {
entries.forEach { if (it.isSelected) this.add(it.catNum) }
}
entriesListener.onEntriesSubmit(catNumList)
dismiss()
}
private fun onNegativeClicked() {
dismiss()
}
private fun onNeutralClicked() {
selectAllToggle = if (selectAllToggle) {
val currentList = entryAdapter.getEntries()
currentList.forEach { it.isSelected = true }
entryAdapter.setEntries(currentList)
false
} else {
val currentList = entryAdapter.getEntries()
currentList.forEach { it.isSelected = false }
entryAdapter.setEntries(currentList)
true
}
}
override fun onQueryTextChange(newText: String): Boolean {
val filteredList = filterEntries(entries, newText)
entryAdapter.setEntries(filteredList)
return false
}
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
interface EntriesSubmitListener {
fun onEntriesSubmit(catNumList: MutableList<Int>)
}
}
@@ -1,81 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.ui.fragments
import android.app.Dialog
import android.os.Bundle
import android.view.ViewGroup
import android.view.Window
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.rtbishop.look4sat.data.TleSource
import com.rtbishop.look4sat.databinding.DialogTleSourcesBinding
import com.rtbishop.look4sat.ui.adapters.TleSourcesAdapter
class TleSourcesDialogFragment(sources: List<TleSource>) :
AppCompatDialogFragment() {
private lateinit var sourcesListener: SourcesSubmitListener
private val emptySource = TleSource("")
private val sourcesAdapter = TleSourcesAdapter(sources.toMutableList())
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogTleSourcesBinding.inflate(requireActivity().layoutInflater)
val tleSourcesDialog = Dialog(requireActivity()).apply {
window?.requestFeature(Window.FEATURE_NO_TITLE)
setContentView(binding.root)
window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
binding.tleSourcesRecycler.apply {
layoutManager = LinearLayoutManager(activity)
adapter = sourcesAdapter
}
binding.tleSourceBtnAdd.setOnClickListener {
val tempSources = sourcesAdapter.getSources()
tempSources.add(emptySource)
sourcesAdapter.setSources(tempSources)
sourcesAdapter.notifyDataSetChanged()
}
binding.tleSourcesBtnNeg.setOnClickListener { dismiss() }
binding.tleSourcesBtnPos.setOnClickListener {
val filteredSources = sourcesAdapter.getSources()
.filter { it.url != String() && it.url != " " && it.url.contains("https://") }
sourcesListener.onSourcesSubmit(filteredSources)
dismiss()
}
return tleSourcesDialog
}
fun setSourcesListener(listener: SourcesSubmitListener): TleSourcesDialogFragment {
sourcesListener = listener
return this
}
interface SourcesSubmitListener {
fun onSourcesSubmit(list: List<TleSource>)
}
}
@@ -1,171 +0,0 @@
package com.rtbishop.look4sat.ui.views
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.view.View
import androidx.core.content.ContextCompat
import com.github.amsacode.predict4java.GroundStationPosition
import com.github.amsacode.predict4java.Position
import com.github.amsacode.predict4java.SatPos
import com.github.amsacode.predict4java.TLE
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.data.SatPass
import java.util.*
import kotlin.math.abs
class MapView(context: Context) : View(context) {
constructor(context: Context, groundStationPosition: GroundStationPosition) : this(context) {
gsp = groundStationPosition
}
private lateinit var passList: List<SatPass>
private lateinit var gsp: GroundStationPosition
private lateinit var selectedSat: TLE
private val scale = resources.displayMetrics.density
private val groundTrackPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.satTrack)
style = Paint.Style.STROKE
strokeWidth = scale
}
private val satPaintPrim = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.satPrimary)
style = Paint.Style.STROKE
strokeWidth = scale
}
private val satPaintSec = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.satSecondary)
style = Paint.Style.STROKE
strokeWidth = scale
}
private val txtPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.satPrimary)
style = Paint.Style.FILL
strokeWidth = scale
textSize = 16f
setShadowLayer(2f, 2f, 2f, Color.BLACK)
}
private val outlinePaint = Paint().apply {
isAntiAlias = true
color = Color.BLACK
style = Paint.Style.FILL_AND_STROKE
strokeWidth = scale
textSize = 16f
}
private val rect = Rect()
private var checked = 0
private var degLon = 0f
private var degLat = 0f
fun setList(satPassList: List<SatPass>) {
passList = satPassList
}
fun setChecked(item: Int) {
checked = item
selectedSat = passList[checked].tle
}
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas) {
degLon = width / 360f
degLat = height / 180f
canvas.translate(width / 2f, height / 2f)
drawHomeLoc(canvas)
val currentTime = Date(System.currentTimeMillis())
val orbitalPeriod = (24 * 60 / selectedSat.meanmo).toInt()
val predictor = passList[checked].predictor
val positions = predictor.getPositions(currentTime, 60, 0, orbitalPeriod * 3)
drawGroundTrack(canvas, positions)
passList.forEach { satPass -> drawSat(canvas, satPass, currentTime, satPaintSec) }
drawSat(canvas, passList[checked], currentTime, satPaintPrim)
}
private fun drawHomeLoc(canvas: Canvas) {
val lon = gsp.longitude.toFloat()
val lat = gsp.latitude.toFloat() * -1
val cx = lon * degLon
val cy = lat * degLat
val gspName = context.getString(R.string.map_gsp)
txtPaint.getTextBounds(gspName, 0, gspName.length, rect)
canvas.drawCircle(cx, cy, scale * 2, txtPaint)
canvas.drawText(gspName, cx - rect.width() / 2, cy - txtPaint.textSize, outlinePaint)
canvas.drawText(gspName, cx - rect.width() / 2, cy - txtPaint.textSize, txtPaint)
}
private fun drawGroundTrack(canvas: Canvas, list: List<SatPos>) {
val path = Path()
var lon: Float
var lat: Float
var lastLon = 181f
list.withIndex().forEach { (index, satPos) ->
lon = Math.toDegrees(satPos.longitude).toFloat()
lat = Math.toDegrees(satPos.latitude).toFloat() * -1
if (lon > 180f) lon -= 360f
lon *= degLon
lat *= degLat
if (index == 0 || abs(lon - lastLon) > 180) path.moveTo(lon, lat)
else path.lineTo(lon, lat)
lastLon = lon
}
canvas.drawPath(path, groundTrackPaint)
}
private fun drawSat(canvas: Canvas, satPass: SatPass, date: Date, paint: Paint) {
val tle = satPass.tle
val predictor = satPass.predictor
val satPosNow = predictor.getSatPos(date)
val footprintPosList = satPosNow.rangeCircle
drawFootprint(canvas, footprintPosList, paint)
drawName(canvas, satPosNow, tle.name)
}
private fun drawFootprint(canvas: Canvas, list: List<Position>, paint: Paint) {
val path = Path()
var lon: Float
var lat: Float
var lastLon = 181f
list.withIndex().forEach { (index, position) ->
lon = position.lon.toFloat()
lat = position.lat.toFloat() * -1
if (lon > 180f) lon -= 360f
lon *= degLon
lat *= degLat
if (index == 0 || abs(lon - lastLon) > 180) path.moveTo(lon, lat)
else path.lineTo(lon, lat)
lastLon = lon
}
canvas.drawPath(path, paint)
}
private fun drawName(canvas: Canvas, position: SatPos, name: String) {
var lon = Math.toDegrees(position.longitude).toFloat()
val lat = Math.toDegrees(position.latitude).toFloat() * -1
if (lon > 180f) lon -= 360f
val cx = lon * degLon
val cy = lat * degLat
canvas.drawCircle(cx, cy, scale * 2, txtPaint)
txtPaint.getTextBounds(name, 0, name.length, rect)
canvas.drawText(name, cx - rect.width() / 2, cy - txtPaint.textSize, outlinePaint)
canvas.drawText(name, cx - rect.width() / 2, cy - txtPaint.textSize, txtPaint)
}
}
@@ -1,117 +0,0 @@
package com.rtbishop.look4sat.ui.views
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.view.View
import androidx.core.content.ContextCompat
import com.rtbishop.look4sat.R
import com.rtbishop.look4sat.data.SatPass
import java.util.*
import kotlin.math.cos
import kotlin.math.sin
class PolarView(context: Context) : View(context) {
constructor(context: Context, satPass: SatPass) : this(context) {
pass = satPass
}
private lateinit var pass: SatPass
private val polarWidth = resources.displayMetrics.widthPixels
private val polarCenter = polarWidth / 2f
private val scale = resources.displayMetrics.density
private val radius = polarWidth * 0.49f
private val txtSize = scale * 15
private val path: Path = Path()
private var azimuth = 0f
private val radarPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.themeLight)
style = Paint.Style.STROKE
strokeWidth = scale
}
private val txtPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.themeAccent)
textSize = txtSize
}
private val trackPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.satTrack)
style = Paint.Style.STROKE
strokeWidth = scale
}
private val satPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.themeAccent)
style = Paint.Style.FILL
}
override fun onDraw(canvas: Canvas) {
canvas.rotate(-azimuth, polarCenter, polarCenter)
canvas.translate(polarCenter, polarCenter)
drawRadarView(canvas)
drawRadarText(canvas)
if (!pass.tle.isDeepspace) {
drawPassTrajectory(canvas, pass)
}
drawSatellite(canvas, pass)
}
private fun drawRadarView(cvs: Canvas) {
cvs.drawLine(-radius, 0f, radius, 0f, radarPaint)
cvs.drawLine(0f, -radius, 0f, radius, radarPaint)
cvs.drawCircle(0f, 0f, radius, radarPaint)
cvs.drawCircle(0f, 0f, (radius / 3) * 2, radarPaint)
cvs.drawCircle(0f, 0f, radius / 3, radarPaint)
}
private fun drawRadarText(cvs: Canvas) {
cvs.drawText("N", scale, -radius + txtSize - scale * 2, txtPaint)
cvs.drawText("30°", scale, -((radius / 3) * 2) - scale * 2, txtPaint)
cvs.drawText("60°", scale, -(radius / 3) - scale * 2, txtPaint)
cvs.drawText("90°", scale, -scale * 2, txtPaint)
}
private fun drawPassTrajectory(cvs: Canvas, satPass: SatPass) {
val startTime = satPass.pass.startTime
val endTime = satPass.pass.endTime
while (startTime.before(endTime)) {
val satPos = satPass.predictor.getSatPos(startTime)
val x = sph2CartX(satPos.azimuth, satPos.elevation, radius.toDouble())
val y = sph2CartY(satPos.azimuth, satPos.elevation, radius.toDouble())
if (startTime.compareTo(satPass.pass.startTime) == 0) {
path.moveTo(x, -y)
} else {
path.lineTo(x, -y)
}
startTime.time += 15000
}
cvs.drawPath(path, trackPaint)
}
private fun drawSatellite(cvs: Canvas, satPass: SatPass) {
val date = Date(System.currentTimeMillis())
val satPos = satPass.predictor.getSatPos(date)
if (satPos.elevation > 0) {
val x = sph2CartX(satPos.azimuth, satPos.elevation, radius.toDouble())
val y = sph2CartY(satPos.azimuth, satPos.elevation, radius.toDouble())
cvs.drawCircle(x, -y, txtSize / 3, satPaint)
}
}
private fun sph2CartX(azimuth: Double, elevation: Double, r: Double): Float {
val piDiv2 = Math.PI / 2.0
val radius = r * (piDiv2 - elevation) / piDiv2
return (radius * cos(piDiv2 - azimuth)).toFloat()
}
private fun sph2CartY(azimuth: Double, elevation: Double, r: Double): Float {
val piDiv2 = Math.PI / 2.0
val radius = r * (piDiv2 - elevation) / piDiv2
return (radius * sin(piDiv2 - azimuth)).toFloat()
}
}
@@ -1,19 +0,0 @@
package com.rtbishop.look4sat.utility
import androidx.room.TypeConverter
import com.github.amsacode.predict4java.TLE
import com.google.gson.Gson
class Converters {
private val gSon = Gson()
@TypeConverter
fun tleToString(tle: TLE): String {
return gSon.toJson(tle)
}
@TypeConverter
fun tleFromString(string: String): TLE {
return gSon.fromJson(string, TLE::class.java)
}
}
@@ -1,11 +0,0 @@
package com.rtbishop.look4sat.utility
import android.content.Context
import android.widget.Toast
object Extensions {
fun String.toast(context: Context, duration: Int = Toast.LENGTH_SHORT): Toast {
return Toast.makeText(context, this, duration).apply { show() }
}
}
@@ -1,269 +0,0 @@
/**
* predict4java: An SDP4 / SGP4 library for satellite orbit predictions
*
* Copyright (C) 2004-2010 David A. B. Johnson, G4DPZ.
*
* This class is a Java port of one of the core elements of
* the Predict program, Copyright John A. Magliacane,
* KD2BD 1991-2003: http://www.qsl.net/kd2bd/predict.html
*
* Dr. T.S. Kelso is the author of the SGP4/SDP4 orbital models,
* originally written in Fortran and Pascal, and released into the
* public domain through his website (http://www.celestrak.com/).
* Neoklis Kyriazis, 5B4AZ, later re-wrote Dr. Kelso's code in C,
* and released it under the GNU GPL in 2002.
* PREDICT's core is based on 5B4AZ's code translation efforts.
*
* Author: David A. B. Johnson, G4DPZ <dave></dave>@g4dpz.me.uk>
*
* Comments, questions and bugreports should be submitted via
* http://sourceforge.net/projects/websat/
* More details can be found at the project home page:
*
* http://websat.sourceforge.net
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, visit http://www.fsf.org/
*/
package com.rtbishop.look4sat.utility
import com.github.amsacode.predict4java.*
import java.util.*
class PassPredictor(private val tle: TLE, private val qth: GroundStationPosition) {
private val sat: Satellite = SatelliteFactory.createSatellite(tle)
private val south = "south"
private val north = "north"
private val deadSpotNone = "none"
private val speedOfLight = 2.99792458E8
private val twoPi = Math.PI * 2.0
private val timeZone: TimeZone = TimeZone.getTimeZone("UTC")
private var iterationCount = 0
fun getDownlinkFreq(freq: Long, date: Date): Long {
val cal = Calendar.getInstance(timeZone).apply {
clear()
timeInMillis = date.time
}
val satPos = getSatPos(cal.time)
val rangeRate = satPos.rangeRate
return (freq.toDouble() * (speedOfLight - rangeRate * 1000.0) / speedOfLight).toLong()
}
fun getUplinkFreq(freq: Long, date: Date): Long {
val cal = Calendar.getInstance(timeZone).apply {
clear()
timeInMillis = date.time
}
val satPos = getSatPos(cal.time)
val rangeRate = satPos.rangeRate
return (freq.toDouble() * (speedOfLight + rangeRate * 1000.0) / speedOfLight).toLong()
}
fun getSatPos(time: Date): SatPos {
iterationCount++
return sat.getPosition(qth, time)
}
fun getPositions(
referenceDate: Date,
incrementSeconds: Int,
minutesBefore: Int,
minutesAfter: Int
): List<SatPos> {
val positions: MutableList<SatPos> = ArrayList()
val endDateDate = Date(referenceDate.time + minutesAfter * 60L * 1000L)
var trackDate = Date(referenceDate.time - minutesBefore * 60L * 1000L)
while (trackDate.before(endDateDate)) {
positions.add(getSatPos(trackDate))
trackDate = Date(trackDate.time + incrementSeconds * 1000)
}
return positions
}
fun getPasses(start: Date, hoursAhead: Int, windBack: Boolean): List<SatPassTime> {
iterationCount = 0
val satellite = SatelliteFactory.createSatellite(tle)
val passes: MutableList<SatPassTime> = ArrayList()
val trackEndDate = Date(start.time + hoursAhead * 60L * 60L * 1000L)
var trackStartDate = start
var windBackTime = windBack
var lastAOS: Date
var count = 0
if (satellite.willBeSeen(qth)) {
if (tle.isDeepspace) passes.add(nextGeoSatPass(start))
else {
do {
if (count > 0) windBackTime = false
val pass = nextSatPass(trackStartDate, windBackTime)
lastAOS = pass.startTime
passes.add(pass)
trackStartDate =
Date(pass.endTime.time + threeQuarterOrbitMinutes() * 60L * 1000L)
count++
} while (lastAOS < trackEndDate)
}
}
return passes
}
private fun nextGeoSatPass(date: Date): SatPassTime {
val aosAzimuth: Int
val losAzimuth: Int
val tca: Date
val polePassed: String
val cal = Calendar.getInstance(timeZone).apply {
clear()
timeInMillis = date.time
}
val satPos = getSatPos(cal.time)
aosAzimuth = (satPos.azimuth / (2.0 * Math.PI) * 360.0).toInt()
losAzimuth = (satPos.azimuth / (2.0 * Math.PI) * 360.0).toInt()
tca = satPos.time
polePassed = getPolePassed(satPos, satPos)
cal.add(Calendar.HOUR, -12)
val startDate = cal.time
cal.add(Calendar.HOUR, 24)
val endDate = cal.time
return SatPassTime(
startDate, endDate, tca, polePassed, aosAzimuth,
losAzimuth, satPos.elevation / (2.0 * Math.PI) * 360.0
)
}
private fun nextSatPass(date: Date, windBack: Boolean = false): SatPassTime {
val aosAzimuth: Int
val losAzimuth: Int
var maxElevation = 0.0
var elevation: Double
var prevPos: SatPos
var polePassed = deadSpotNone
// get the current position
val cal = Calendar.getInstance(timeZone).apply {
clear()
timeInMillis = date.time
}
// wind back time 1/4 of an orbit
if (windBack) {
val meanMotion = tle.meanmo
cal.add(Calendar.MINUTE, (-24.0 * 60.0 / meanMotion / 4.0).toInt())
}
var satPos = getSatPos(cal.time)
// test for the elevation being above the horizon
if (satPos.elevation > 0.0) {
// move time forward in 30 second intervals until the sat goes below the horizon
do {
satPos = getPosition(cal, 60)
} while (satPos.elevation > 0.0)
// move time forward 3/4 orbit
cal.add(Calendar.MINUTE, threeQuarterOrbitMinutes())
}
// now find the next time it comes above the horizon
do {
satPos = getPosition(cal, 60)
elevation = satPos.elevation
if (elevation > maxElevation) {
maxElevation = elevation
}
} while (satPos.elevation < 0.0)
// refine it to 5 seconds
cal.add(Calendar.SECOND, -60)
do {
satPos = getPosition(cal, 5)
elevation = satPos.elevation
if (elevation > maxElevation) {
maxElevation = elevation
}
prevPos = satPos
} while (satPos.elevation < 0.0)
val startDate = satPos.time
aosAzimuth = (satPos.azimuth / (2.0 * Math.PI) * 360.0).toInt()
// now find when it goes below
do {
satPos = getPosition(cal, 30)
val currPolePassed = getPolePassed(prevPos, satPos)
if (currPolePassed != deadSpotNone) {
polePassed = currPolePassed
}
elevation = satPos.elevation
if (elevation > maxElevation) {
maxElevation = elevation
}
prevPos = satPos
} while (satPos.elevation > 0.0)
// refine it to 5 seconds
cal.add(Calendar.SECOND, -30)
do {
satPos = getPosition(cal, 5)
elevation = satPos.elevation
if (elevation > maxElevation) {
maxElevation = elevation
}
} while (satPos.elevation > 0.0)
val endDate = satPos.time
losAzimuth = (satPos.azimuth / (2.0 * Math.PI) * 360.0).toInt()
val tca = Date(startDate.time + (endDate.time - startDate.time) / 2)
return SatPassTime(
startDate, endDate, tca, polePassed, aosAzimuth,
losAzimuth, maxElevation / (2.0 * Math.PI) * 360.0
)
}
private fun getPosition(cal: Calendar, offSet: Int): SatPos {
cal.add(Calendar.SECOND, offSet)
return getSatPos(cal.time)
}
private fun getPolePassed(prevPos: SatPos, satPos: SatPos): String {
var polePassed = deadSpotNone
val az1 = prevPos.azimuth / twoPi * 360.0
val az2 = satPos.azimuth / twoPi * 360.0
if (az1 > az2) {
// we may be moving from 350 or greater through north
if (az1 > 350 && az2 < 10) polePassed = north
else {
// we may be moving from 190 or greater through south
if (az1 > 180 && az2 < 180) polePassed = south
}
} else {
// we may be moving from 10 or less through north
if (az1 < 10 && az2 > 350) polePassed = north
else {
// we may be moving from 170 or more through south
if (az1 < 180 && az2 > 180) polePassed = south
}
}
return polePassed
}
private fun threeQuarterOrbitMinutes(): Int {
return (24.0 * 60.0 / tle.meanmo * 0.75).toInt()
}
}
@@ -1,124 +0,0 @@
/*
* Look4Sat. Amateur radio and weather satellite tracker and passes predictor for Android.
* Copyright (C) 2019, 2020 Arty Bishop (bishop.arty@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.rtbishop.look4sat.utility
import android.content.SharedPreferences
import android.location.Location
import android.location.LocationManager
import androidx.core.content.edit
import com.github.amsacode.predict4java.GroundStationPosition
import javax.inject.Inject
class PrefsManager @Inject constructor(
private val preferences: SharedPreferences,
private val locationManager: LocationManager
) {
private val keyHoursAhead = "hoursAhead"
private val keyMinElevation = "minEl"
private val keyLatitude = "latitude"
private val keyLongitude = "longitude"
private val keyAltitude = "altitude"
private val keyRefreshRate = "rate"
private val keyCompass = "compass"
private val keyTimeUtc = "timeUTC"
private val defaultHoursAhead = 8
private val defaultMinEl = 16.0
private val defaultRefreshRate = "3000"
private val defaultGSP = "0.0"
fun isFirstLaunch(): Boolean {
val keyIsFirstLaunch = "keyIsFirstLaunch"
val isFirstLaunch = preferences.getBoolean(keyIsFirstLaunch, true)
return if (isFirstLaunch) {
preferences.edit {
putBoolean(keyIsFirstLaunch, false)
apply()
}
true
} else isFirstLaunch
}
fun isTimeUTC(): Boolean {
return preferences.getBoolean(keyTimeUtc, false)
}
fun getHoursAhead(): Int {
return preferences.getInt(keyHoursAhead, defaultHoursAhead)
}
fun getMinElevation(): Double {
return preferences.getDouble(keyMinElevation, defaultMinEl)
}
fun getRefreshRate(): Long {
return preferences.getString(keyRefreshRate, defaultRefreshRate)!!.toLong()
}
fun getCompass(): Boolean {
return preferences.getBoolean(keyCompass, true)
}
fun getPosition(): GroundStationPosition {
val lat = preferences.getString(keyLatitude, defaultGSP)!!.toDouble()
val lon = preferences.getString(keyLongitude, defaultGSP)!!.toDouble()
val alt = preferences.getString(keyAltitude, defaultGSP)!!.toDouble()
return GroundStationPosition(lat, lon, alt)
}
fun getLastKnownLocation(): Location? {
val provPassive = LocationManager.PASSIVE_PROVIDER
return try {
val location = locationManager.getLastKnownLocation(provPassive)
location?.let {
preferences.edit {
putString(keyLatitude, location.latitude.toString())
putString(keyLongitude, location.longitude.toString())
putString(keyAltitude, location.altitude.toString())
apply()
}
}
location
} catch (e: SecurityException) {
null
}
}
fun setHoursAhead(hours: Int) {
preferences.edit {
putInt(keyHoursAhead, hours)
apply()
}
}
fun setMinElevation(minEl: Double) {
preferences.edit {
putDouble(keyMinElevation, minEl)
apply()
}
}
private fun SharedPreferences.Editor.putDouble(key: String, double: Double) {
putLong(key, double.toRawBits())
}
private fun SharedPreferences.getDouble(key: String, default: Double): Double {
return Double.fromBits(getLong(key, default.toRawBits()))
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more