├── .gitattributes ├── .gitignore ├── .travis.yml ├── AndroidManifest.xml ├── LICENSE ├── README.md ├── assets └── webserver │ ├── 404.html │ ├── css │ ├── codemirror.css │ ├── fullscreen.css │ └── show-hint.css │ ├── favicon.ico │ ├── index.html │ └── lib │ ├── codemirror-compressed.js │ └── mode │ └── javascript │ └── javascript.js ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── ic_launcher-web.png ├── lint.xml ├── proguard-project.txt ├── project.properties ├── res ├── drawable-hdpi │ └── ic_launcher.png ├── drawable-ldpi │ └── ic_launcher.png ├── drawable-mdpi │ └── ic_launcher.png ├── drawable-xhdpi │ └── ic_launcher.png ├── layout │ └── activity_main.xml ├── menu │ └── activity_main.xml ├── values-v11 │ └── styles.xml ├── values-v14 │ └── styles.xml ├── values │ ├── strings.xml │ ├── strings_activity_settings.xml │ └── styles.xml └── xml │ ├── pref_general.xml │ └── pref_headers.xml ├── src └── com │ └── appspot │ └── usbhidterminal │ ├── SettingsActivity.java │ ├── USBHIDTerminal.java │ └── core │ ├── Consts.java │ ├── USBUtils.java │ ├── events │ ├── DeviceAttachedEvent.java │ ├── DeviceDetachedEvent.java │ ├── LogMessageEvent.java │ ├── PrepareDevicesListEvent.java │ ├── SelectDeviceEvent.java │ ├── ShowDevicesListEvent.java │ ├── USBDataReceiveEvent.java │ └── USBDataSendEvent.java │ ├── services │ ├── AbstractUSBHIDService.java │ ├── SocketService.java │ ├── USBHIDService.java │ └── WebServerService.java │ └── webserver │ ├── WebServer.java │ └── Ws.java └── tests ├── AndroidManifest.xml └── src └── com └── appspot └── usbhidterminal └── tests ├── SocketServiceTest.java └── UITest.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | gen/ 10 | tmp/ 11 | *.tmp 12 | *.bak 13 | *.swp 14 | *~.nib 15 | local.properties 16 | .classpath 17 | .settings/ 18 | .loadpath 19 | 20 | # External tool builders 21 | .externalToolBuilders/ 22 | 23 | # Locally stored "Eclipse launch configurations" 24 | *.launch 25 | 26 | # CDT-specific 27 | .cproject 28 | 29 | # PDT-specific 30 | .buildpath 31 | 32 | 33 | ################# 34 | ## Visual Studio 35 | ################# 36 | 37 | ## Ignore Visual Studio temporary files, build results, and 38 | ## files generated by popular Visual Studio add-ons. 39 | 40 | # User-specific files 41 | *.suo 42 | *.user 43 | *.sln.docstates 44 | 45 | # Build results 46 | 47 | [Dd]ebug/ 48 | [Rr]elease/ 49 | x64/ 50 | build/ 51 | [Bb]in/ 52 | [Oo]bj/ 53 | 54 | # MSTest test Results 55 | [Tt]est[Rr]esult*/ 56 | [Bb]uild[Ll]og.* 57 | 58 | *_i.c 59 | *_p.c 60 | *.ilk 61 | *.meta 62 | *.obj 63 | *.pch 64 | *.pdb 65 | *.pgc 66 | *.pgd 67 | *.rsp 68 | *.sbr 69 | *.tlb 70 | *.tli 71 | *.tlh 72 | *.tmp 73 | *.tmp_proj 74 | *.log 75 | *.vspscc 76 | *.vssscc 77 | .builds 78 | *.pidb 79 | *.log 80 | *.scc 81 | 82 | # Visual C++ cache files 83 | ipch/ 84 | *.aps 85 | *.ncb 86 | *.opensdf 87 | *.sdf 88 | *.cachefile 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | 102 | # TeamCity is a build add-in 103 | _TeamCity* 104 | 105 | # DotCover is a Code Coverage Tool 106 | *.dotCover 107 | 108 | # NCrunch 109 | *.ncrunch* 110 | .*crunch*.local.xml 111 | 112 | # Installshield output folder 113 | [Ee]xpress/ 114 | 115 | # DocProject is a documentation generator add-in 116 | DocProject/buildhelp/ 117 | DocProject/Help/*.HxT 118 | DocProject/Help/*.HxC 119 | DocProject/Help/*.hhc 120 | DocProject/Help/*.hhk 121 | DocProject/Help/*.hhp 122 | DocProject/Help/Html2 123 | DocProject/Help/html 124 | 125 | # Click-Once directory 126 | publish/ 127 | 128 | # Publish Web Output 129 | *.Publish.xml 130 | *.pubxml 131 | 132 | # NuGet Packages Directory 133 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 134 | #packages/ 135 | 136 | # Windows Azure Build Output 137 | csx 138 | *.build.csdef 139 | 140 | # Windows Store app package directory 141 | AppPackages/ 142 | 143 | # Others 144 | sql/ 145 | *.Cache 146 | ClientBin/ 147 | [Ss]tyle[Cc]op.* 148 | ~$* 149 | *~ 150 | *.dbmdl 151 | *.[Pp]ublish.xml 152 | *.pfx 153 | *.publishsettings 154 | 155 | # RIA/Silverlight projects 156 | Generated_Code/ 157 | 158 | # Backup & report files from converting an old project file to a newer 159 | # Visual Studio version. Backup files are not needed, because we have git ;-) 160 | _UpgradeReport_Files/ 161 | Backup*/ 162 | UpgradeLog*.XML 163 | UpgradeLog*.htm 164 | 165 | # SQL Server files 166 | App_Data/*.mdf 167 | App_Data/*.ldf 168 | 169 | ############# 170 | ## Windows detritus 171 | ############# 172 | 173 | # Windows image file caches 174 | Thumbs.db 175 | ehthumbs.db 176 | 177 | # Folder config file 178 | Desktop.ini 179 | 180 | # Recycle Bin used on file shares 181 | $RECYCLE.BIN/ 182 | 183 | # Mac crap 184 | .DS_Store 185 | 186 | 187 | ############# 188 | ## Python 189 | ############# 190 | 191 | *.py[co] 192 | 193 | # Packages 194 | *.egg 195 | *.egg-info 196 | dist/ 197 | build/ 198 | eggs/ 199 | parts/ 200 | var/ 201 | sdist/ 202 | develop-eggs/ 203 | .installed.cfg 204 | 205 | # Installer logs 206 | pip-log.txt 207 | 208 | # Unit test / coverage reports 209 | .coverage 210 | .tox 211 | 212 | #Translations 213 | *.mo 214 | 215 | #Mr Developer 216 | .mr.developer.cfg 217 | /.gradle/ 218 | .idea 219 | captures/ 220 | *.iml 221 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | jdk: 4 | - openjdk8 5 | 6 | sudo: false 7 | 8 | android: 9 | components: 10 | - build-tools-29.0.2 11 | - android-29 12 | - extra 13 | 14 | os: 15 | - linux 16 | 17 | before_install: 18 | - yes | sdkmanager "platforms;android-27" 19 | - yes | sdkmanager "platforms;android-29" 20 | 21 | before_cache: 22 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 23 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 24 | cache: 25 | directories: 26 | - $HOME/.gradle/caches/ 27 | - $HOME/.gradle/wrapper/ 28 | - $HOME/.android/build-cache 29 | 30 | script: 31 | - echo "Travis branch is $TRAVIS_BRANCH" 32 | - echo "Travis branch is in pull request $TRAVIS_PULL+REQUEST" 33 | - ./gradlew assembleRelease 34 | -------------------------------------------------------------------------------- /AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 23 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 38 | 42 | 46 | 47 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | USBHIDTerminal for Android 2 | ============== 3 | [![Build Status](https://travis-ci.org/452/USBHIDTerminal.svg?branch=develop)](https://travis-ci.org/452/USBHIDTerminal) 4 | 5 | This application was created in my hobby time. 6 | 7 | USB HID Terminal provide access to HID USB devices. 8 | HID Terminal can be used for transfer any commands or any data to your USB HID devices. 9 | USB HID Terminal - can receive and send bytes, hex, binary, text. 10 | 11 | https://play.google.com/store/apps/details?id=com.appspot.usbhidterminal 12 | 13 | binary APK: 14 | https://github.com/452/USBHIDTerminalAPKRepo 15 | 16 | for Gradle: [https://docs.gradle.org/current/userguide/installation.html] 17 | 18 | $ git clone https://github.com/452/USBHIDTerminal.git 19 | $ cd USBHIDTerminal 20 | $ ./gradlew build 21 | 22 | result you can find: 23 | > USBHIDTerminal/build/outputs/apk/USBHIDTerminal-release-unsigned.apk 24 | 25 | If you have some problem or want to improve this application you can help me, or just say me about this. 26 | We can make this world better. 27 | 28 | ;) Ukraine 29 | 30 | ## LICENSE 31 | 32 | Copyright 2024 452 emetemunoy. 33 | 34 | Licensed under the Apache License, Version 2.0 (the "License"); 35 | you may not use this file except in compliance with the License. 36 | You may obtain a copy of the License at 37 | 38 | 39 | 40 | Unless required by applicable law or agreed to in writing, software 41 | distributed under the License is distributed on an "AS IS" BASIS, 42 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 43 | See the License for the specific language governing permissions and 44 | limitations under the License. 45 | -------------------------------------------------------------------------------- /assets/webserver/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 404 6 | 7 | 8 |

404

9 | 10 | -------------------------------------------------------------------------------- /assets/webserver/css/codemirror.css: -------------------------------------------------------------------------------- 1 | /* BASICS */ 2 | 3 | .CodeMirror { 4 | /* Set height, width, borders, and global font properties here */ 5 | font-family: monospace; 6 | height: 300px; 7 | color: black; 8 | } 9 | 10 | /* PADDING */ 11 | 12 | .CodeMirror-lines { 13 | padding: 4px 0; /* Vertical padding around content */ 14 | } 15 | .CodeMirror pre { 16 | padding: 0 4px; /* Horizontal padding of content */ 17 | } 18 | 19 | .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { 20 | background-color: white; /* The little square between H and V scrollbars */ 21 | } 22 | 23 | /* GUTTER */ 24 | 25 | .CodeMirror-gutters { 26 | border-right: 1px solid #ddd; 27 | background-color: #f7f7f7; 28 | white-space: nowrap; 29 | } 30 | .CodeMirror-linenumbers {} 31 | .CodeMirror-linenumber { 32 | padding: 0 3px 0 5px; 33 | min-width: 20px; 34 | text-align: right; 35 | color: #999; 36 | white-space: nowrap; 37 | } 38 | 39 | .CodeMirror-guttermarker { color: black; } 40 | .CodeMirror-guttermarker-subtle { color: #999; } 41 | 42 | /* CURSOR */ 43 | 44 | .CodeMirror div.CodeMirror-cursor { 45 | border-left: 1px solid black; 46 | } 47 | /* Shown when moving in bi-directional text */ 48 | .CodeMirror div.CodeMirror-secondarycursor { 49 | border-left: 1px solid silver; 50 | } 51 | .CodeMirror.cm-fat-cursor div.CodeMirror-cursor { 52 | width: auto; 53 | border: 0; 54 | background: #7e7; 55 | } 56 | .CodeMirror.cm-fat-cursor div.CodeMirror-cursors { 57 | z-index: 1; 58 | } 59 | 60 | .cm-animate-fat-cursor { 61 | width: auto; 62 | border: 0; 63 | -webkit-animation: blink 1.06s steps(1) infinite; 64 | -moz-animation: blink 1.06s steps(1) infinite; 65 | animation: blink 1.06s steps(1) infinite; 66 | } 67 | @-moz-keyframes blink { 68 | 0% { background: #7e7; } 69 | 50% { background: none; } 70 | 100% { background: #7e7; } 71 | } 72 | @-webkit-keyframes blink { 73 | 0% { background: #7e7; } 74 | 50% { background: none; } 75 | 100% { background: #7e7; } 76 | } 77 | @keyframes blink { 78 | 0% { background: #7e7; } 79 | 50% { background: none; } 80 | 100% { background: #7e7; } 81 | } 82 | 83 | /* Can style cursor different in overwrite (non-insert) mode */ 84 | div.CodeMirror-overwrite div.CodeMirror-cursor {} 85 | 86 | .cm-tab { display: inline-block; text-decoration: inherit; } 87 | 88 | .CodeMirror-ruler { 89 | border-left: 1px solid #ccc; 90 | position: absolute; 91 | } 92 | 93 | /* DEFAULT THEME */ 94 | 95 | .cm-s-default .cm-keyword {color: #708;} 96 | .cm-s-default .cm-atom {color: #219;} 97 | .cm-s-default .cm-number {color: #164;} 98 | .cm-s-default .cm-def {color: #00f;} 99 | .cm-s-default .cm-variable, 100 | .cm-s-default .cm-punctuation, 101 | .cm-s-default .cm-property, 102 | .cm-s-default .cm-operator {} 103 | .cm-s-default .cm-variable-2 {color: #05a;} 104 | .cm-s-default .cm-variable-3 {color: #085;} 105 | .cm-s-default .cm-comment {color: #a50;} 106 | .cm-s-default .cm-string {color: #a11;} 107 | .cm-s-default .cm-string-2 {color: #f50;} 108 | .cm-s-default .cm-meta {color: #555;} 109 | .cm-s-default .cm-qualifier {color: #555;} 110 | .cm-s-default .cm-builtin {color: #30a;} 111 | .cm-s-default .cm-bracket {color: #997;} 112 | .cm-s-default .cm-tag {color: #170;} 113 | .cm-s-default .cm-attribute {color: #00c;} 114 | .cm-s-default .cm-header {color: blue;} 115 | .cm-s-default .cm-quote {color: #090;} 116 | .cm-s-default .cm-hr {color: #999;} 117 | .cm-s-default .cm-link {color: #00c;} 118 | 119 | .cm-negative {color: #d44;} 120 | .cm-positive {color: #292;} 121 | .cm-header, .cm-strong {font-weight: bold;} 122 | .cm-em {font-style: italic;} 123 | .cm-link {text-decoration: underline;} 124 | .cm-strikethrough {text-decoration: line-through;} 125 | 126 | .cm-s-default .cm-error {color: #f00;} 127 | .cm-invalidchar {color: #f00;} 128 | 129 | .CodeMirror-composing { border-bottom: 2px solid; } 130 | 131 | /* Default styles for common addons */ 132 | 133 | div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} 134 | div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} 135 | .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } 136 | .CodeMirror-activeline-background {background: #e8f2ff;} 137 | 138 | /* STOP */ 139 | 140 | /* The rest of this file contains styles related to the mechanics of 141 | the editor. You probably shouldn't touch them. */ 142 | 143 | .CodeMirror { 144 | position: relative; 145 | overflow: hidden; 146 | background: white; 147 | } 148 | 149 | .CodeMirror-scroll { 150 | overflow: scroll !important; /* Things will break if this is overridden */ 151 | /* 30px is the magic margin used to hide the element's real scrollbars */ 152 | /* See overflow: hidden in .CodeMirror */ 153 | margin-bottom: -30px; margin-right: -30px; 154 | padding-bottom: 30px; 155 | height: 100%; 156 | outline: none; /* Prevent dragging from highlighting the element */ 157 | position: relative; 158 | } 159 | .CodeMirror-sizer { 160 | position: relative; 161 | border-right: 30px solid transparent; 162 | } 163 | 164 | /* The fake, visible scrollbars. Used to force redraw during scrolling 165 | before actuall scrolling happens, thus preventing shaking and 166 | flickering artifacts. */ 167 | .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { 168 | position: absolute; 169 | z-index: 6; 170 | display: none; 171 | } 172 | .CodeMirror-vscrollbar { 173 | right: 0; top: 0; 174 | overflow-x: hidden; 175 | overflow-y: scroll; 176 | } 177 | .CodeMirror-hscrollbar { 178 | bottom: 0; left: 0; 179 | overflow-y: hidden; 180 | overflow-x: scroll; 181 | } 182 | .CodeMirror-scrollbar-filler { 183 | right: 0; bottom: 0; 184 | } 185 | .CodeMirror-gutter-filler { 186 | left: 0; bottom: 0; 187 | } 188 | 189 | .CodeMirror-gutters { 190 | position: absolute; left: 0; top: 0; 191 | z-index: 3; 192 | } 193 | .CodeMirror-gutter { 194 | white-space: normal; 195 | height: 100%; 196 | display: inline-block; 197 | margin-bottom: -30px; 198 | /* Hack to make IE7 behave */ 199 | *zoom:1; 200 | *display:inline; 201 | } 202 | .CodeMirror-gutter-wrapper { 203 | position: absolute; 204 | z-index: 4; 205 | height: 100%; 206 | } 207 | .CodeMirror-gutter-elt { 208 | position: absolute; 209 | cursor: default; 210 | z-index: 4; 211 | } 212 | .CodeMirror-gutter-wrapper { 213 | -webkit-user-select: none; 214 | -moz-user-select: none; 215 | user-select: none; 216 | } 217 | 218 | .CodeMirror-lines { 219 | cursor: text; 220 | min-height: 1px; /* prevents collapsing before first draw */ 221 | } 222 | .CodeMirror pre { 223 | /* Reset some styles that the rest of the page might have set */ 224 | -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; 225 | border-width: 0; 226 | background: transparent; 227 | font-family: inherit; 228 | font-size: inherit; 229 | margin: 0; 230 | white-space: pre; 231 | word-wrap: normal; 232 | line-height: inherit; 233 | color: inherit; 234 | z-index: 2; 235 | position: relative; 236 | overflow: visible; 237 | -webkit-tap-highlight-color: transparent; 238 | } 239 | .CodeMirror-wrap pre { 240 | word-wrap: break-word; 241 | white-space: pre-wrap; 242 | word-break: normal; 243 | } 244 | 245 | .CodeMirror-linebackground { 246 | position: absolute; 247 | left: 0; right: 0; top: 0; bottom: 0; 248 | z-index: 0; 249 | } 250 | 251 | .CodeMirror-linewidget { 252 | position: relative; 253 | z-index: 2; 254 | overflow: auto; 255 | } 256 | 257 | .CodeMirror-widget {} 258 | 259 | .CodeMirror-code { 260 | outline: none; 261 | } 262 | 263 | /* Force content-box sizing for the elements where we expect it */ 264 | .CodeMirror-scroll, 265 | .CodeMirror-sizer, 266 | .CodeMirror-gutter, 267 | .CodeMirror-gutters, 268 | .CodeMirror-linenumber { 269 | -moz-box-sizing: content-box; 270 | box-sizing: content-box; 271 | } 272 | 273 | .CodeMirror-measure { 274 | position: absolute; 275 | width: 100%; 276 | height: 0; 277 | overflow: hidden; 278 | visibility: hidden; 279 | } 280 | .CodeMirror-measure pre { position: static; } 281 | 282 | .CodeMirror div.CodeMirror-cursor { 283 | position: absolute; 284 | border-right: none; 285 | width: 0; 286 | } 287 | 288 | div.CodeMirror-cursors { 289 | visibility: hidden; 290 | position: relative; 291 | z-index: 3; 292 | } 293 | .CodeMirror-focused div.CodeMirror-cursors { 294 | visibility: visible; 295 | } 296 | 297 | .CodeMirror-selected { background: #d9d9d9; } 298 | .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } 299 | .CodeMirror-crosshair { cursor: crosshair; } 300 | .CodeMirror ::selection { background: #d7d4f0; } 301 | .CodeMirror ::-moz-selection { background: #d7d4f0; } 302 | 303 | .cm-searching { 304 | background: #ffa; 305 | background: rgba(255, 255, 0, .4); 306 | } 307 | 308 | /* IE7 hack to prevent it from returning funny offsetTops on the spans */ 309 | .CodeMirror span { *vertical-align: text-bottom; } 310 | 311 | /* Used to force a border model for a node */ 312 | .cm-force-border { padding-right: .1px; } 313 | 314 | @media print { 315 | /* Hide the cursor when printing */ 316 | .CodeMirror div.CodeMirror-cursors { 317 | visibility: hidden; 318 | } 319 | } 320 | 321 | /* See issue #2901 */ 322 | .cm-tab-wrap-hack:after { content: ''; } 323 | 324 | /* Help users use markselection to safely style text background */ 325 | span.CodeMirror-selectedtext { background: none; } 326 | -------------------------------------------------------------------------------- /assets/webserver/css/fullscreen.css: -------------------------------------------------------------------------------- 1 | .CodeMirror-fullscreen { 2 | position: fixed; 3 | top: 0; left: 0; right: 0; bottom: 0; 4 | height: auto; 5 | z-index: 9; 6 | } 7 | -------------------------------------------------------------------------------- /assets/webserver/css/show-hint.css: -------------------------------------------------------------------------------- 1 | .CodeMirror-hints { 2 | position: absolute; 3 | z-index: 10; 4 | overflow: hidden; 5 | list-style: none; 6 | 7 | margin: 0; 8 | padding: 2px; 9 | 10 | -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); 11 | -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); 12 | box-shadow: 2px 3px 5px rgba(0,0,0,.2); 13 | border-radius: 3px; 14 | border: 1px solid silver; 15 | 16 | background: white; 17 | font-size: 90%; 18 | font-family: monospace; 19 | 20 | max-height: 20em; 21 | overflow-y: auto; 22 | } 23 | 24 | .CodeMirror-hint { 25 | margin: 0; 26 | padding: 0 4px; 27 | border-radius: 2px; 28 | max-width: 19em; 29 | overflow: hidden; 30 | white-space: pre; 31 | color: black; 32 | cursor: pointer; 33 | } 34 | 35 | li.CodeMirror-hint-active { 36 | background: #08f; 37 | color: white; 38 | } 39 | -------------------------------------------------------------------------------- /assets/webserver/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/assets/webserver/favicon.ico -------------------------------------------------------------------------------- /assets/webserver/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | USB HID Terminal 6 | 7 | 8 | 9 | 10 | 36 | 166 | 167 |
168 |
169 |

USB HID Terminal 1.1.1

170 |
171 | Your custom JavaScript code (F11, CTRL+SPACE, CTRL+D, CTRL+Q): 172 |
173 | 189 |
190 | 191 |
192 | ping: 193 |
194 | 195 | 196 | 197 | 198 |
199 |
200 |
201 | 205 | 206 | -------------------------------------------------------------------------------- /assets/webserver/lib/mode/javascript/javascript.js: -------------------------------------------------------------------------------- 1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others 2 | // Distributed under an MIT license: http://codemirror.net/LICENSE 3 | 4 | // TODO actually recognize syntax of TypeScript constructs 5 | 6 | (function(mod) { 7 | if (typeof exports == "object" && typeof module == "object") // CommonJS 8 | mod(require("../../lib/codemirror")); 9 | else if (typeof define == "function" && define.amd) // AMD 10 | define(["../../lib/codemirror"], mod); 11 | else // Plain browser env 12 | mod(CodeMirror); 13 | })(function(CodeMirror) { 14 | "use strict"; 15 | 16 | CodeMirror.defineMode("javascript", function(config, parserConfig) { 17 | var indentUnit = config.indentUnit; 18 | var statementIndent = parserConfig.statementIndent; 19 | var jsonldMode = parserConfig.jsonld; 20 | var jsonMode = parserConfig.json || jsonldMode; 21 | var isTS = parserConfig.typescript; 22 | var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; 23 | 24 | // Tokenizer 25 | 26 | var keywords = function(){ 27 | function kw(type) {return {type: type, style: "keyword"};} 28 | var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); 29 | var operator = kw("operator"), atom = {type: "atom", style: "atom"}; 30 | 31 | var jsKeywords = { 32 | "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, 33 | "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C, 34 | "var": kw("var"), "const": kw("var"), "let": kw("var"), 35 | "function": kw("function"), "catch": kw("catch"), 36 | "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), 37 | "in": operator, "typeof": operator, "instanceof": operator, 38 | "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, 39 | "this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"), 40 | "yield": C, "export": kw("export"), "import": kw("import"), "extends": C 41 | }; 42 | 43 | // Extend the 'normal' keywords with the TypeScript language extensions 44 | if (isTS) { 45 | var type = {type: "variable", style: "variable-3"}; 46 | var tsKeywords = { 47 | // object-like things 48 | "interface": kw("interface"), 49 | "extends": kw("extends"), 50 | "constructor": kw("constructor"), 51 | 52 | // scope modifiers 53 | "public": kw("public"), 54 | "private": kw("private"), 55 | "protected": kw("protected"), 56 | "static": kw("static"), 57 | 58 | // types 59 | "string": type, "number": type, "bool": type, "any": type 60 | }; 61 | 62 | for (var attr in tsKeywords) { 63 | jsKeywords[attr] = tsKeywords[attr]; 64 | } 65 | } 66 | 67 | return jsKeywords; 68 | }(); 69 | 70 | var isOperatorChar = /[+\-*&%=<>!?|~^]/; 71 | var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; 72 | 73 | function readRegexp(stream) { 74 | var escaped = false, next, inSet = false; 75 | while ((next = stream.next()) != null) { 76 | if (!escaped) { 77 | if (next == "/" && !inSet) return; 78 | if (next == "[") inSet = true; 79 | else if (inSet && next == "]") inSet = false; 80 | } 81 | escaped = !escaped && next == "\\"; 82 | } 83 | } 84 | 85 | // Used as scratch variables to communicate multiple values without 86 | // consing up tons of objects. 87 | var type, content; 88 | function ret(tp, style, cont) { 89 | type = tp; content = cont; 90 | return style; 91 | } 92 | function tokenBase(stream, state) { 93 | var ch = stream.next(); 94 | if (ch == '"' || ch == "'") { 95 | state.tokenize = tokenString(ch); 96 | return state.tokenize(stream, state); 97 | } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { 98 | return ret("number", "number"); 99 | } else if (ch == "." && stream.match("..")) { 100 | return ret("spread", "meta"); 101 | } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { 102 | return ret(ch); 103 | } else if (ch == "=" && stream.eat(">")) { 104 | return ret("=>", "operator"); 105 | } else if (ch == "0" && stream.eat(/x/i)) { 106 | stream.eatWhile(/[\da-f]/i); 107 | return ret("number", "number"); 108 | } else if (/\d/.test(ch)) { 109 | stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); 110 | return ret("number", "number"); 111 | } else if (ch == "/") { 112 | if (stream.eat("*")) { 113 | state.tokenize = tokenComment; 114 | return tokenComment(stream, state); 115 | } else if (stream.eat("/")) { 116 | stream.skipToEnd(); 117 | return ret("comment", "comment"); 118 | } else if (state.lastType == "operator" || state.lastType == "keyword c" || 119 | state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) { 120 | readRegexp(stream); 121 | stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/); 122 | return ret("regexp", "string-2"); 123 | } else { 124 | stream.eatWhile(isOperatorChar); 125 | return ret("operator", "operator", stream.current()); 126 | } 127 | } else if (ch == "`") { 128 | state.tokenize = tokenQuasi; 129 | return tokenQuasi(stream, state); 130 | } else if (ch == "#") { 131 | stream.skipToEnd(); 132 | return ret("error", "error"); 133 | } else if (isOperatorChar.test(ch)) { 134 | stream.eatWhile(isOperatorChar); 135 | return ret("operator", "operator", stream.current()); 136 | } else if (wordRE.test(ch)) { 137 | stream.eatWhile(wordRE); 138 | var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; 139 | return (known && state.lastType != ".") ? ret(known.type, known.style, word) : 140 | ret("variable", "variable", word); 141 | } 142 | } 143 | 144 | function tokenString(quote) { 145 | return function(stream, state) { 146 | var escaped = false, next; 147 | if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ 148 | state.tokenize = tokenBase; 149 | return ret("jsonld-keyword", "meta"); 150 | } 151 | while ((next = stream.next()) != null) { 152 | if (next == quote && !escaped) break; 153 | escaped = !escaped && next == "\\"; 154 | } 155 | if (!escaped) state.tokenize = tokenBase; 156 | return ret("string", "string"); 157 | }; 158 | } 159 | 160 | function tokenComment(stream, state) { 161 | var maybeEnd = false, ch; 162 | while (ch = stream.next()) { 163 | if (ch == "/" && maybeEnd) { 164 | state.tokenize = tokenBase; 165 | break; 166 | } 167 | maybeEnd = (ch == "*"); 168 | } 169 | return ret("comment", "comment"); 170 | } 171 | 172 | function tokenQuasi(stream, state) { 173 | var escaped = false, next; 174 | while ((next = stream.next()) != null) { 175 | if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { 176 | state.tokenize = tokenBase; 177 | break; 178 | } 179 | escaped = !escaped && next == "\\"; 180 | } 181 | return ret("quasi", "string-2", stream.current()); 182 | } 183 | 184 | var brackets = "([{}])"; 185 | // This is a crude lookahead trick to try and notice that we're 186 | // parsing the argument patterns for a fat-arrow function before we 187 | // actually hit the arrow token. It only works if the arrow is on 188 | // the same line as the arguments and there's no strange noise 189 | // (comments) in between. Fallback is to only notice when we hit the 190 | // arrow, and not declare the arguments as locals for the arrow 191 | // body. 192 | function findFatArrow(stream, state) { 193 | if (state.fatArrowAt) state.fatArrowAt = null; 194 | var arrow = stream.string.indexOf("=>", stream.start); 195 | if (arrow < 0) return; 196 | 197 | var depth = 0, sawSomething = false; 198 | for (var pos = arrow - 1; pos >= 0; --pos) { 199 | var ch = stream.string.charAt(pos); 200 | var bracket = brackets.indexOf(ch); 201 | if (bracket >= 0 && bracket < 3) { 202 | if (!depth) { ++pos; break; } 203 | if (--depth == 0) break; 204 | } else if (bracket >= 3 && bracket < 6) { 205 | ++depth; 206 | } else if (wordRE.test(ch)) { 207 | sawSomething = true; 208 | } else if (/["'\/]/.test(ch)) { 209 | return; 210 | } else if (sawSomething && !depth) { 211 | ++pos; 212 | break; 213 | } 214 | } 215 | if (sawSomething && !depth) state.fatArrowAt = pos; 216 | } 217 | 218 | // Parser 219 | 220 | var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; 221 | 222 | function JSLexical(indented, column, type, align, prev, info) { 223 | this.indented = indented; 224 | this.column = column; 225 | this.type = type; 226 | this.prev = prev; 227 | this.info = info; 228 | if (align != null) this.align = align; 229 | } 230 | 231 | function inScope(state, varname) { 232 | for (var v = state.localVars; v; v = v.next) 233 | if (v.name == varname) return true; 234 | for (var cx = state.context; cx; cx = cx.prev) { 235 | for (var v = cx.vars; v; v = v.next) 236 | if (v.name == varname) return true; 237 | } 238 | } 239 | 240 | function parseJS(state, style, type, content, stream) { 241 | var cc = state.cc; 242 | // Communicate our context to the combinators. 243 | // (Less wasteful than consing up a hundred closures on every call.) 244 | cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; 245 | 246 | if (!state.lexical.hasOwnProperty("align")) 247 | state.lexical.align = true; 248 | 249 | while(true) { 250 | var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; 251 | if (combinator(type, content)) { 252 | while(cc.length && cc[cc.length - 1].lex) 253 | cc.pop()(); 254 | if (cx.marked) return cx.marked; 255 | if (type == "variable" && inScope(state, content)) return "variable-2"; 256 | return style; 257 | } 258 | } 259 | } 260 | 261 | // Combinator utils 262 | 263 | var cx = {state: null, column: null, marked: null, cc: null}; 264 | function pass() { 265 | for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); 266 | } 267 | function cont() { 268 | pass.apply(null, arguments); 269 | return true; 270 | } 271 | function register(varname) { 272 | function inList(list) { 273 | for (var v = list; v; v = v.next) 274 | if (v.name == varname) return true; 275 | return false; 276 | } 277 | var state = cx.state; 278 | if (state.context) { 279 | cx.marked = "def"; 280 | if (inList(state.localVars)) return; 281 | state.localVars = {name: varname, next: state.localVars}; 282 | } else { 283 | if (inList(state.globalVars)) return; 284 | if (parserConfig.globalVars) 285 | state.globalVars = {name: varname, next: state.globalVars}; 286 | } 287 | } 288 | 289 | // Combinators 290 | 291 | var defaultVars = {name: "this", next: {name: "arguments"}}; 292 | function pushcontext() { 293 | cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; 294 | cx.state.localVars = defaultVars; 295 | } 296 | function popcontext() { 297 | cx.state.localVars = cx.state.context.vars; 298 | cx.state.context = cx.state.context.prev; 299 | } 300 | function pushlex(type, info) { 301 | var result = function() { 302 | var state = cx.state, indent = state.indented; 303 | if (state.lexical.type == "stat") indent = state.lexical.indented; 304 | else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) 305 | indent = outer.indented; 306 | state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); 307 | }; 308 | result.lex = true; 309 | return result; 310 | } 311 | function poplex() { 312 | var state = cx.state; 313 | if (state.lexical.prev) { 314 | if (state.lexical.type == ")") 315 | state.indented = state.lexical.indented; 316 | state.lexical = state.lexical.prev; 317 | } 318 | } 319 | poplex.lex = true; 320 | 321 | function expect(wanted) { 322 | function exp(type) { 323 | if (type == wanted) return cont(); 324 | else if (wanted == ";") return pass(); 325 | else return cont(exp); 326 | }; 327 | return exp; 328 | } 329 | 330 | function statement(type, value) { 331 | if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); 332 | if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); 333 | if (type == "keyword b") return cont(pushlex("form"), statement, poplex); 334 | if (type == "{") return cont(pushlex("}"), block, poplex); 335 | if (type == ";") return cont(); 336 | if (type == "if") { 337 | if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) 338 | cx.state.cc.pop()(); 339 | return cont(pushlex("form"), expression, statement, poplex, maybeelse); 340 | } 341 | if (type == "function") return cont(functiondef); 342 | if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); 343 | if (type == "variable") return cont(pushlex("stat"), maybelabel); 344 | if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), 345 | block, poplex, poplex); 346 | if (type == "case") return cont(expression, expect(":")); 347 | if (type == "default") return cont(expect(":")); 348 | if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), 349 | statement, poplex, popcontext); 350 | if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex); 351 | if (type == "class") return cont(pushlex("form"), className, poplex); 352 | if (type == "export") return cont(pushlex("form"), afterExport, poplex); 353 | if (type == "import") return cont(pushlex("form"), afterImport, poplex); 354 | return pass(pushlex("stat"), expression, expect(";"), poplex); 355 | } 356 | function expression(type) { 357 | return expressionInner(type, false); 358 | } 359 | function expressionNoComma(type) { 360 | return expressionInner(type, true); 361 | } 362 | function expressionInner(type, noComma) { 363 | if (cx.state.fatArrowAt == cx.stream.start) { 364 | var body = noComma ? arrowBodyNoComma : arrowBody; 365 | if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); 366 | else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); 367 | } 368 | 369 | var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; 370 | if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); 371 | if (type == "function") return cont(functiondef, maybeop); 372 | if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); 373 | if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); 374 | if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); 375 | if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); 376 | if (type == "{") return contCommasep(objprop, "}", null, maybeop); 377 | if (type == "quasi") { return pass(quasi, maybeop); } 378 | return cont(); 379 | } 380 | function maybeexpression(type) { 381 | if (type.match(/[;\}\)\],]/)) return pass(); 382 | return pass(expression); 383 | } 384 | function maybeexpressionNoComma(type) { 385 | if (type.match(/[;\}\)\],]/)) return pass(); 386 | return pass(expressionNoComma); 387 | } 388 | 389 | function maybeoperatorComma(type, value) { 390 | if (type == ",") return cont(expression); 391 | return maybeoperatorNoComma(type, value, false); 392 | } 393 | function maybeoperatorNoComma(type, value, noComma) { 394 | var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; 395 | var expr = noComma == false ? expression : expressionNoComma; 396 | if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); 397 | if (type == "operator") { 398 | if (/\+\+|--/.test(value)) return cont(me); 399 | if (value == "?") return cont(expression, expect(":"), expr); 400 | return cont(expr); 401 | } 402 | if (type == "quasi") { return pass(quasi, me); } 403 | if (type == ";") return; 404 | if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); 405 | if (type == ".") return cont(property, me); 406 | if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); 407 | } 408 | function quasi(type, value) { 409 | if (type != "quasi") return pass(); 410 | if (value.slice(value.length - 2) != "${") return cont(quasi); 411 | return cont(expression, continueQuasi); 412 | } 413 | function continueQuasi(type) { 414 | if (type == "}") { 415 | cx.marked = "string-2"; 416 | cx.state.tokenize = tokenQuasi; 417 | return cont(quasi); 418 | } 419 | } 420 | function arrowBody(type) { 421 | findFatArrow(cx.stream, cx.state); 422 | return pass(type == "{" ? statement : expression); 423 | } 424 | function arrowBodyNoComma(type) { 425 | findFatArrow(cx.stream, cx.state); 426 | return pass(type == "{" ? statement : expressionNoComma); 427 | } 428 | function maybelabel(type) { 429 | if (type == ":") return cont(poplex, statement); 430 | return pass(maybeoperatorComma, expect(";"), poplex); 431 | } 432 | function property(type) { 433 | if (type == "variable") {cx.marked = "property"; return cont();} 434 | } 435 | function objprop(type, value) { 436 | if (type == "variable" || cx.style == "keyword") { 437 | cx.marked = "property"; 438 | if (value == "get" || value == "set") return cont(getterSetter); 439 | return cont(afterprop); 440 | } else if (type == "number" || type == "string") { 441 | cx.marked = jsonldMode ? "property" : (cx.style + " property"); 442 | return cont(afterprop); 443 | } else if (type == "jsonld-keyword") { 444 | return cont(afterprop); 445 | } else if (type == "[") { 446 | return cont(expression, expect("]"), afterprop); 447 | } 448 | } 449 | function getterSetter(type) { 450 | if (type != "variable") return pass(afterprop); 451 | cx.marked = "property"; 452 | return cont(functiondef); 453 | } 454 | function afterprop(type) { 455 | if (type == ":") return cont(expressionNoComma); 456 | if (type == "(") return pass(functiondef); 457 | } 458 | function commasep(what, end) { 459 | function proceed(type) { 460 | if (type == ",") { 461 | var lex = cx.state.lexical; 462 | if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; 463 | return cont(what, proceed); 464 | } 465 | if (type == end) return cont(); 466 | return cont(expect(end)); 467 | } 468 | return function(type) { 469 | if (type == end) return cont(); 470 | return pass(what, proceed); 471 | }; 472 | } 473 | function contCommasep(what, end, info) { 474 | for (var i = 3; i < arguments.length; i++) 475 | cx.cc.push(arguments[i]); 476 | return cont(pushlex(end, info), commasep(what, end), poplex); 477 | } 478 | function block(type) { 479 | if (type == "}") return cont(); 480 | return pass(statement, block); 481 | } 482 | function maybetype(type) { 483 | if (isTS && type == ":") return cont(typedef); 484 | } 485 | function typedef(type) { 486 | if (type == "variable"){cx.marked = "variable-3"; return cont();} 487 | } 488 | function vardef() { 489 | return pass(pattern, maybetype, maybeAssign, vardefCont); 490 | } 491 | function pattern(type, value) { 492 | if (type == "variable") { register(value); return cont(); } 493 | if (type == "[") return contCommasep(pattern, "]"); 494 | if (type == "{") return contCommasep(proppattern, "}"); 495 | } 496 | function proppattern(type, value) { 497 | if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { 498 | register(value); 499 | return cont(maybeAssign); 500 | } 501 | if (type == "variable") cx.marked = "property"; 502 | return cont(expect(":"), pattern, maybeAssign); 503 | } 504 | function maybeAssign(_type, value) { 505 | if (value == "=") return cont(expressionNoComma); 506 | } 507 | function vardefCont(type) { 508 | if (type == ",") return cont(vardef); 509 | } 510 | function maybeelse(type, value) { 511 | if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); 512 | } 513 | function forspec(type) { 514 | if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); 515 | } 516 | function forspec1(type) { 517 | if (type == "var") return cont(vardef, expect(";"), forspec2); 518 | if (type == ";") return cont(forspec2); 519 | if (type == "variable") return cont(formaybeinof); 520 | return pass(expression, expect(";"), forspec2); 521 | } 522 | function formaybeinof(_type, value) { 523 | if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } 524 | return cont(maybeoperatorComma, forspec2); 525 | } 526 | function forspec2(type, value) { 527 | if (type == ";") return cont(forspec3); 528 | if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } 529 | return pass(expression, expect(";"), forspec3); 530 | } 531 | function forspec3(type) { 532 | if (type != ")") cont(expression); 533 | } 534 | function functiondef(type, value) { 535 | if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} 536 | if (type == "variable") {register(value); return cont(functiondef);} 537 | if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext); 538 | } 539 | function funarg(type) { 540 | if (type == "spread") return cont(funarg); 541 | return pass(pattern, maybetype); 542 | } 543 | function className(type, value) { 544 | if (type == "variable") {register(value); return cont(classNameAfter);} 545 | } 546 | function classNameAfter(type, value) { 547 | if (value == "extends") return cont(expression, classNameAfter); 548 | if (type == "{") return cont(pushlex("}"), classBody, poplex); 549 | } 550 | function classBody(type, value) { 551 | if (type == "variable" || cx.style == "keyword") { 552 | if (value == "static") { 553 | cx.marked = "keyword"; 554 | return cont(classBody); 555 | } 556 | cx.marked = "property"; 557 | if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody); 558 | return cont(functiondef, classBody); 559 | } 560 | if (value == "*") { 561 | cx.marked = "keyword"; 562 | return cont(classBody); 563 | } 564 | if (type == ";") return cont(classBody); 565 | if (type == "}") return cont(); 566 | } 567 | function classGetterSetter(type) { 568 | if (type != "variable") return pass(); 569 | cx.marked = "property"; 570 | return cont(); 571 | } 572 | function afterModule(type, value) { 573 | if (type == "string") return cont(statement); 574 | if (type == "variable") { register(value); return cont(maybeFrom); } 575 | } 576 | function afterExport(_type, value) { 577 | if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } 578 | if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } 579 | return pass(statement); 580 | } 581 | function afterImport(type) { 582 | if (type == "string") return cont(); 583 | return pass(importSpec, maybeFrom); 584 | } 585 | function importSpec(type, value) { 586 | if (type == "{") return contCommasep(importSpec, "}"); 587 | if (type == "variable") register(value); 588 | if (value == "*") cx.marked = "keyword"; 589 | return cont(maybeAs); 590 | } 591 | function maybeAs(_type, value) { 592 | if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } 593 | } 594 | function maybeFrom(_type, value) { 595 | if (value == "from") { cx.marked = "keyword"; return cont(expression); } 596 | } 597 | function arrayLiteral(type) { 598 | if (type == "]") return cont(); 599 | return pass(expressionNoComma, maybeArrayComprehension); 600 | } 601 | function maybeArrayComprehension(type) { 602 | if (type == "for") return pass(comprehension, expect("]")); 603 | if (type == ",") return cont(commasep(maybeexpressionNoComma, "]")); 604 | return pass(commasep(expressionNoComma, "]")); 605 | } 606 | function comprehension(type) { 607 | if (type == "for") return cont(forspec, comprehension); 608 | if (type == "if") return cont(expression, comprehension); 609 | } 610 | 611 | function isContinuedStatement(state, textAfter) { 612 | return state.lastType == "operator" || state.lastType == "," || 613 | isOperatorChar.test(textAfter.charAt(0)) || 614 | /[,.]/.test(textAfter.charAt(0)); 615 | } 616 | 617 | // Interface 618 | 619 | return { 620 | startState: function(basecolumn) { 621 | var state = { 622 | tokenize: tokenBase, 623 | lastType: "sof", 624 | cc: [], 625 | lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), 626 | localVars: parserConfig.localVars, 627 | context: parserConfig.localVars && {vars: parserConfig.localVars}, 628 | indented: 0 629 | }; 630 | if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") 631 | state.globalVars = parserConfig.globalVars; 632 | return state; 633 | }, 634 | 635 | token: function(stream, state) { 636 | if (stream.sol()) { 637 | if (!state.lexical.hasOwnProperty("align")) 638 | state.lexical.align = false; 639 | state.indented = stream.indentation(); 640 | findFatArrow(stream, state); 641 | } 642 | if (state.tokenize != tokenComment && stream.eatSpace()) return null; 643 | var style = state.tokenize(stream, state); 644 | if (type == "comment") return style; 645 | state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; 646 | return parseJS(state, style, type, content, stream); 647 | }, 648 | 649 | indent: function(state, textAfter) { 650 | if (state.tokenize == tokenComment) return CodeMirror.Pass; 651 | if (state.tokenize != tokenBase) return 0; 652 | var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; 653 | // Kludge to prevent 'maybelse' from blocking lexical scope pops 654 | if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { 655 | var c = state.cc[i]; 656 | if (c == poplex) lexical = lexical.prev; 657 | else if (c != maybeelse) break; 658 | } 659 | if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; 660 | if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") 661 | lexical = lexical.prev; 662 | var type = lexical.type, closing = firstChar == type; 663 | 664 | if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); 665 | else if (type == "form" && firstChar == "{") return lexical.indented; 666 | else if (type == "form") return lexical.indented + indentUnit; 667 | else if (type == "stat") 668 | return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); 669 | else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) 670 | return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); 671 | else if (lexical.align) return lexical.column + (closing ? 0 : 1); 672 | else return lexical.indented + (closing ? 0 : indentUnit); 673 | }, 674 | 675 | electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, 676 | blockCommentStart: jsonMode ? null : "/*", 677 | blockCommentEnd: jsonMode ? null : "*/", 678 | lineComment: jsonMode ? null : "//", 679 | fold: "brace", 680 | closeBrackets: "()[]{}''\"\"``", 681 | 682 | helperType: jsonMode ? "json" : "javascript", 683 | jsonldMode: jsonldMode, 684 | jsonMode: jsonMode 685 | }; 686 | }); 687 | 688 | CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); 689 | 690 | CodeMirror.defineMIME("text/javascript", "javascript"); 691 | CodeMirror.defineMIME("text/ecmascript", "javascript"); 692 | CodeMirror.defineMIME("application/javascript", "javascript"); 693 | CodeMirror.defineMIME("application/x-javascript", "javascript"); 694 | CodeMirror.defineMIME("application/ecmascript", "javascript"); 695 | CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); 696 | CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); 697 | CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); 698 | CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); 699 | CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); 700 | 701 | }); 702 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | ext { 4 | versionMajor = 1 5 | versionMinor = 1 6 | } 7 | 8 | buildscript { 9 | repositories { 10 | google() 11 | mavenCentral() 12 | jcenter() 13 | } 14 | 15 | dependencies { 16 | classpath 'com.android.tools.build:gradle:8.5.2' 17 | 18 | // NOTE: Do not place your application dependencies here; they belong 19 | // in the individual module build.gradle files 20 | } 21 | } 22 | 23 | repositories { 24 | google() 25 | mavenCentral() 26 | } 27 | 28 | dependencies { 29 | implementation 'androidx.core:core:1.13.1' 30 | implementation 'com.nanohttpd:nanohttpd:2.1.1' 31 | implementation 'com.nanohttpd:nanohttpd-websocket:2.1.1' 32 | implementation 'org.greenrobot:eventbus:3.3.1' 33 | // Testing-only dependencies 34 | androidTestImplementation "androidx.test:core:1.6.1"; 35 | androidTestImplementation "androidx.test.ext:junit:1.2.1"; 36 | androidTestImplementation "androidx.test:runner:1.6.1"; 37 | androidTestImplementation "androidx.test:rules:1.6.1"; 38 | } 39 | 40 | android { 41 | 42 | namespace 'com.appspot.usbhidterminal' 43 | 44 | compileSdk 34 45 | 46 | defaultConfig { 47 | applicationId "com.appspot.usbhidterminal" 48 | minSdkVersion 21 49 | targetSdkVersion 34 50 | versionCode computeVersionCode() 51 | versionName computeVersionName() 52 | } 53 | 54 | buildTypes { 55 | release { 56 | minifyEnabled false 57 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 58 | } 59 | } 60 | compileOptions { 61 | sourceCompatibility JavaVersion.VERSION_1_8 62 | targetCompatibility JavaVersion.VERSION_1_8 63 | } 64 | 65 | sourceSets { 66 | main { 67 | manifest.srcFile 'AndroidManifest.xml' 68 | java.srcDirs = ['src'] 69 | res.srcDirs = ['res'] 70 | assets.srcDirs = ['assets'] 71 | } 72 | androidTest.setRoot('tests') 73 | androidTest.java.srcDirs = ['tests/src'] 74 | } 75 | packagingOptions { 76 | resources { 77 | excludes += ['META-INF/DEPENDENCIES.txt', 'META-INF/DEPENDENCIES', 'META-INF/dependencies.txt', 'META-INF/LICENSE.txt', 'META-INF/LICENSE', 'META-INF/license.txt', 'META-INF/LGPL2.1', 'META-INF/NOTICE.txt', 'META-INF/NOTICE', 'META-INF/notice.txt', 'LICENSE.txt'] 78 | } 79 | } 80 | lint { 81 | abortOnError false 82 | } 83 | 84 | } 85 | 86 | task adbConfig(type: Exec) { 87 | commandLine 'adb', 'connect', '192.168.1.45:5555' 88 | } 89 | 90 | 91 | task tst(dependsOn: ['adbConfig', 'connectedAndroidTest']) { 92 | 93 | } 94 | 95 | def computeVersionName() { 96 | // Basic . version name 97 | return String.format('%d.%d', versionMajor, versionMinor) 98 | } 99 | 100 | // Will return 120042 for Jenkins build #42 101 | def computeVersionCode() { 102 | // Major + minor + Jenkins build number (where available) 103 | return (versionMajor * 10) + (versionMinor * 10) + Integer.valueOf(System.env.BUILD_NUMBER ?: 0) 104 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | android.nonTransitiveRClass=false 21 | android.nonFinalResIds=false 22 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/ic_launcher-web.png -------------------------------------------------------------------------------- /lint.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -keepclassmembers class ** { 22 | public void onEvent*(**); 23 | } -------------------------------------------------------------------------------- /project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-22 15 | -------------------------------------------------------------------------------- /res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /res/drawable-ldpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/res/drawable-ldpi/ic_launcher.png -------------------------------------------------------------------------------- /res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/452/USBHIDTerminal/be9aaa916169fefe4ba4bbf53a9a4357049d1a4b/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 62 | 63 | 72 | 73 | 79 | 80 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /res/menu/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 14 | 15 | 18 | 21 | 24 | 27 | 30 | 31 | 32 | 33 | 36 | 37 | 39 | 42 | 45 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /res/values-v11/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /res/values-v14/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 11 | 12 | -------------------------------------------------------------------------------- /res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | USB HID Terminal 4 | Web Server 5 | Socket Server 6 | Exit 7 | Settings 8 | Receive data format 9 | Integer 10 | Hexadecimal 11 | Binary 12 | Char 13 | Delimiter 14 | Delimiter - None 15 | Delimiter - New Line 16 | Delimiter - Space 17 | Connected 18 | Disconnected 19 | Select HID device 20 | Send 21 | Clear 22 | Send Text 23 | Binary (15 #F 017) 24 | 25 | -------------------------------------------------------------------------------- /res/values/strings_activity_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | Settings 3 | 4 | 5 | General 6 | Enable WebServer - BETA Version 7 | Enable SocketServer 8 | Web Server port 9 | 7799 10 | Socket Server port 11 | 7899 12 | -------------------------------------------------------------------------------- /res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | -------------------------------------------------------------------------------- /res/xml/pref_general.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 11 | 12 | 13 | 23 | 32 | -------------------------------------------------------------------------------- /res/xml/pref_headers.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 |
5 | -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/SettingsActivity.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal; 2 | 3 | import android.annotation.TargetApi; 4 | import android.content.Context; 5 | import android.content.res.Configuration; 6 | import android.os.Build; 7 | import android.os.Bundle; 8 | import android.preference.ListPreference; 9 | import android.preference.Preference; 10 | import android.preference.PreferenceActivity; 11 | import android.preference.PreferenceFragment; 12 | import android.preference.PreferenceManager; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * A {@link PreferenceActivity} that presents a set of application settings. On 18 | * handset devices, settings are presented as a single list. On tablets, 19 | * settings are split by category, with category headers shown to the left of 20 | * the list of settings. 21 | *

22 | * See 23 | * Android Design: Settings for design guidelines and the Settings 25 | * API Guide for more information on developing a Settings UI. 26 | */ 27 | public class SettingsActivity extends PreferenceActivity { 28 | /** 29 | * Determines whether to always show the simplified settings UI, where 30 | * settings are presented in a single list. When false, settings are shown 31 | * as a master/detail two-pane view on tablets. When true, a single pane is 32 | * shown on tablets. 33 | */ 34 | private static final boolean ALWAYS_SIMPLE_PREFS = false; 35 | 36 | 37 | @Override 38 | protected void onPostCreate(Bundle savedInstanceState) { 39 | super.onPostCreate(savedInstanceState); 40 | setupSimplePreferencesScreen(); 41 | } 42 | 43 | /** 44 | * Shows the simplified settings UI if the device configuration if the 45 | * device configuration dictates that a simplified, single-pane UI should be 46 | * shown. 47 | */ 48 | private void setupSimplePreferencesScreen() { 49 | if (!isSimplePreferences(this)) { 50 | return; 51 | } 52 | 53 | // In the simplified UI, fragments are not used at all and we instead 54 | // use the older PreferenceActivity APIs. 55 | 56 | // Add 'general' preferences. 57 | addPreferencesFromResource(R.xml.pref_general); 58 | 59 | // Bind the summaries of EditText/List/Dialog/Ringtone preferences to 60 | // their values. When their values change, their summaries are updated 61 | // to reflect the new value, per the Android Design guidelines. 62 | bindPreferenceSummaryToValue(findPreference("web_server_port")); 63 | bindPreferenceSummaryToValue(findPreference("socket_server_port")); 64 | } 65 | 66 | /** 67 | * {@inheritDoc} 68 | */ 69 | @Override 70 | public boolean onIsMultiPane() { 71 | return isXLargeTablet(this) && !isSimplePreferences(this); 72 | } 73 | 74 | /** 75 | * Helper method to determine if the device has an extra-large screen. For 76 | * example, 10" tablets are extra-large. 77 | */ 78 | private static boolean isXLargeTablet(Context context) { 79 | return (context.getResources().getConfiguration().screenLayout 80 | & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; 81 | } 82 | 83 | /** 84 | * Determines whether the simplified settings UI should be shown. This is 85 | * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device 86 | * doesn't have newer APIs like {@link PreferenceFragment}, or the device 87 | * doesn't have an extra-large screen. In these cases, a single-pane 88 | * "simplified" settings UI should be shown. 89 | */ 90 | private static boolean isSimplePreferences(Context context) { 91 | return ALWAYS_SIMPLE_PREFS 92 | || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB 93 | || !isXLargeTablet(context); 94 | } 95 | 96 | /** 97 | * {@inheritDoc} 98 | */ 99 | @Override 100 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 101 | public void onBuildHeaders(List

target) { 102 | if (!isSimplePreferences(this)) { 103 | loadHeadersFromResource(R.xml.pref_headers, target); 104 | } 105 | } 106 | 107 | /** 108 | * A preference value change listener that updates the preference's summary 109 | * to reflect its new value. 110 | */ 111 | private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { 112 | @Override 113 | public boolean onPreferenceChange(Preference preference, Object value) { 114 | String stringValue = value.toString(); 115 | 116 | if (preference instanceof ListPreference) { 117 | // For list preferences, look up the correct display value in 118 | // the preference's 'entries' list. 119 | ListPreference listPreference = (ListPreference) preference; 120 | int index = listPreference.findIndexOfValue(stringValue); 121 | 122 | // Set the summary to reflect the new value. 123 | preference.setSummary( 124 | index >= 0 125 | ? listPreference.getEntries()[index] 126 | : null); 127 | 128 | } else { 129 | // For all other preferences, set the summary to the value's 130 | // simple string representation. 131 | preference.setSummary(stringValue); 132 | } 133 | return true; 134 | } 135 | }; 136 | 137 | /** 138 | * Binds a preference's summary to its value. More specifically, when the 139 | * preference's value is changed, its summary (line of text below the 140 | * preference title) is updated to reflect the value. The summary is also 141 | * immediately updated upon calling this method. The exact display format is 142 | * dependent on the type of preference. 143 | * 144 | * @see #sBindPreferenceSummaryToValueListener 145 | */ 146 | private static void bindPreferenceSummaryToValue(Preference preference) { 147 | // Set the listener to watch for value changes. 148 | preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); 149 | 150 | // Trigger the listener immediately with the preference's 151 | // current value. 152 | sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, 153 | PreferenceManager 154 | .getDefaultSharedPreferences(preference.getContext()) 155 | .getString(preference.getKey(), "")); 156 | } 157 | 158 | /** 159 | * This fragment shows general preferences only. It is used when the 160 | * activity is showing a two-pane settings UI. 161 | */ 162 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 163 | public static class GeneralPreferenceFragment extends PreferenceFragment { 164 | @Override 165 | public void onCreate(Bundle savedInstanceState) { 166 | super.onCreate(savedInstanceState); 167 | addPreferencesFromResource(R.xml.pref_general); 168 | 169 | // Bind the summaries of EditText/List/Dialog/Ringtone preferences 170 | // to their values. When their values change, their summaries are 171 | // updated to reflect the new value, per the Android Design 172 | // guidelines. 173 | bindPreferenceSummaryToValue(findPreference("web_server_port")); 174 | bindPreferenceSummaryToValue(findPreference("socket_server_port")); 175 | } 176 | } 177 | 178 | /** 179 | * This fragment shows notification preferences only. It is used when the 180 | * activity is showing a two-pane settings UI. 181 | */ 182 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 183 | public static class NotificationPreferenceFragment extends PreferenceFragment { 184 | @Override 185 | public void onCreate(Bundle savedInstanceState) { 186 | super.onCreate(savedInstanceState); 187 | // Bind the summaries of EditText/List/Dialog/Ringtone preferences 188 | // to their values. When their values change, their summaries are 189 | // updated to reflect the new value, per the Android Design 190 | // guidelines. 191 | } 192 | } 193 | 194 | /** 195 | * This fragment shows data and sync preferences only. It is used when the 196 | * activity is showing a two-pane settings UI. 197 | */ 198 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 199 | public static class DataSyncPreferenceFragment extends PreferenceFragment { 200 | @Override 201 | public void onCreate(Bundle savedInstanceState) { 202 | super.onCreate(savedInstanceState); 203 | // Bind the summaries of EditText/List/Dialog/Ringtone preferences 204 | // to their values. When their values change, their summaries are 205 | // updated to reflect the new value, per the Android Design 206 | // guidelines. 207 | } 208 | } 209 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/USBHIDTerminal.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog; 5 | import android.app.NotificationManager; 6 | import android.content.DialogInterface; 7 | import android.content.Intent; 8 | import android.content.SharedPreferences; 9 | import android.content.pm.PackageManager.NameNotFoundException; 10 | import android.os.Bundle; 11 | import android.preference.PreferenceManager; 12 | import android.view.Menu; 13 | import android.view.MenuItem; 14 | import android.view.View; 15 | import android.view.WindowManager; 16 | import android.widget.Button; 17 | import android.widget.EditText; 18 | import android.widget.RadioButton; 19 | 20 | import com.appspot.usbhidterminal.core.Consts; 21 | import com.appspot.usbhidterminal.core.events.DeviceAttachedEvent; 22 | import com.appspot.usbhidterminal.core.events.DeviceDetachedEvent; 23 | import com.appspot.usbhidterminal.core.events.LogMessageEvent; 24 | import com.appspot.usbhidterminal.core.events.PrepareDevicesListEvent; 25 | import com.appspot.usbhidterminal.core.events.SelectDeviceEvent; 26 | import com.appspot.usbhidterminal.core.events.ShowDevicesListEvent; 27 | import com.appspot.usbhidterminal.core.events.USBDataReceiveEvent; 28 | import com.appspot.usbhidterminal.core.events.USBDataSendEvent; 29 | import com.appspot.usbhidterminal.core.services.SocketService; 30 | import com.appspot.usbhidterminal.core.services.USBHIDService; 31 | import com.appspot.usbhidterminal.core.services.WebServerService; 32 | 33 | import org.greenrobot.eventbus.EventBus; 34 | import org.greenrobot.eventbus.EventBusException; 35 | import org.greenrobot.eventbus.Subscribe; 36 | import org.greenrobot.eventbus.ThreadMode; 37 | 38 | public class USBHIDTerminal extends Activity implements View.OnClickListener { 39 | 40 | private SharedPreferences sharedPreferences; 41 | 42 | private Intent usbService; 43 | 44 | private EditText edtlogText; 45 | private EditText edtxtHidInput; 46 | private Button btnSend; 47 | private Button btnSelectHIDDevice; 48 | private Button btnClear; 49 | private RadioButton rbSendText; 50 | private RadioButton rbSendDataType; 51 | private String settingsDelimiter; 52 | 53 | private String receiveDataFormat; 54 | private String delimiter; 55 | 56 | protected EventBus eventBus; 57 | 58 | private final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() { 59 | @Override 60 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 61 | if ("enable_socket_server".equals(key) || "socket_server_port".equals(key)) { 62 | socketServiceIsStart(false); 63 | socketServiceIsStart(sharedPreferences.getBoolean("enable_socket_server", false)); 64 | } else if ("enable_web_server".equals(key) || "web_server_port".equals(key)) { 65 | webServerServiceIsStart(false); 66 | webServerServiceIsStart(sharedPreferences.getBoolean("enable_web_server", false)); 67 | } 68 | } 69 | }; 70 | 71 | private void prepareServices() { 72 | usbService = new Intent(this, USBHIDService.class); 73 | startService(usbService); 74 | webServerServiceIsStart(sharedPreferences.getBoolean("enable_web_server", false)); 75 | socketServiceIsStart(sharedPreferences.getBoolean("enable_socket_server", false)); 76 | } 77 | 78 | @Override 79 | protected void onCreate(Bundle savedInstanceState) { 80 | super.onCreate(savedInstanceState); 81 | setContentView(R.layout.activity_main); 82 | try { 83 | eventBus = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).installDefaultEventBus(); 84 | } catch (EventBusException e) { 85 | eventBus = EventBus.getDefault(); 86 | } 87 | sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 88 | sharedPreferences.registerOnSharedPreferenceChangeListener(listener); 89 | initUI(); 90 | } 91 | 92 | private void initUI() { 93 | setVersionToTitle(); 94 | btnSend = (Button) findViewById(R.id.btnSend); 95 | btnSend.setOnClickListener(this); 96 | 97 | btnSelectHIDDevice = (Button) findViewById(R.id.btnSelectHIDDevice); 98 | btnSelectHIDDevice.setOnClickListener(this); 99 | 100 | btnClear = (Button) findViewById(R.id.btnClear); 101 | btnClear.setOnClickListener(this); 102 | 103 | edtxtHidInput = (EditText) findViewById(R.id.edtxtHidInput); 104 | edtlogText = (EditText) findViewById(R.id.edtlogText); 105 | 106 | rbSendDataType = (RadioButton) findViewById(R.id.rbSendData); 107 | rbSendText = (RadioButton) findViewById(R.id.rbSendText); 108 | rbSendDataType.setOnClickListener(this); 109 | rbSendText.setOnClickListener(this); 110 | 111 | mLog("Development plan:\nUI refactoring\nPossibility to choice interfaces, endpoints, bulk or control transfer\n", false); 112 | mLog("Check Arduino DigiUSB\n", false); 113 | mLog("Check Javaino\n", false); 114 | mLog("Initialized\nPlease select your USB HID device\n", false); 115 | getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 116 | edtxtHidInput.setText("test"); 117 | } 118 | 119 | public void onClick(View v) { 120 | if (v == btnSend) { 121 | eventBus.post(new USBDataSendEvent(edtxtHidInput.getText().toString())); 122 | } else if (v == rbSendText || v == rbSendDataType) { 123 | sendToUSBService(Consts.ACTION_USB_DATA_TYPE, rbSendDataType.isChecked()); 124 | } else if (v == btnClear) { 125 | edtlogText.setText(""); 126 | } else if (v == btnSelectHIDDevice) { 127 | eventBus.post(new PrepareDevicesListEvent()); 128 | } 129 | } 130 | 131 | void showListOfDevices(CharSequence devicesName[]) { 132 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 133 | 134 | if (devicesName.length == 0) { 135 | builder.setTitle(Consts.MESSAGE_CONNECT_YOUR_USB_HID_DEVICE); 136 | } else { 137 | builder.setTitle(Consts.MESSAGE_SELECT_YOUR_USB_HID_DEVICE); 138 | } 139 | 140 | builder.setItems(devicesName, new DialogInterface.OnClickListener() { 141 | @Override 142 | public void onClick(DialogInterface dialog, int which) { 143 | eventBus.post(new SelectDeviceEvent(which)); 144 | } 145 | }); 146 | builder.setCancelable(true); 147 | builder.show(); 148 | } 149 | 150 | @Subscribe(threadMode = ThreadMode.MAIN) 151 | public void onEvent(USBDataReceiveEvent event) { 152 | mLog(event.getData() + " \nReceived " + event.getBytesCount() + " bytes", true); 153 | } 154 | 155 | @Subscribe(threadMode = ThreadMode.MAIN) 156 | public void onEvent(LogMessageEvent event) { 157 | mLog(event.getData(), true); 158 | } 159 | 160 | @Subscribe(threadMode = ThreadMode.MAIN) 161 | public void onEvent(ShowDevicesListEvent event) { 162 | showListOfDevices(event.getCharSequenceArray()); 163 | } 164 | 165 | @Subscribe(threadMode = ThreadMode.MAIN) 166 | public void onEvent(DeviceAttachedEvent event) { 167 | btnSend.setEnabled(true); 168 | } 169 | 170 | @Subscribe(threadMode = ThreadMode.MAIN) 171 | public void onEvent(DeviceDetachedEvent event) { 172 | btnSend.setEnabled(false); 173 | } 174 | 175 | @Override 176 | protected void onStart() { 177 | super.onStart(); 178 | receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT); 179 | prepareServices(); 180 | setDelimiter(); 181 | eventBus.register(this); 182 | } 183 | 184 | @Override 185 | protected void onStop() { 186 | eventBus.unregister(this); 187 | super.onStop(); 188 | } 189 | 190 | @Override 191 | public boolean onCreateOptionsMenu(Menu menu) { 192 | getMenuInflater().inflate(R.menu.activity_main, menu); 193 | setSelectedMenuItemsFromSettings(menu); 194 | return true; 195 | } 196 | 197 | private void setSelectedMenuItemsFromSettings(Menu menu) { 198 | receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT); 199 | if (receiveDataFormat != null) { 200 | if (receiveDataFormat.equals(Consts.BINARY)) { 201 | menu.findItem(R.id.menuSettingsReceiveBinary).setChecked(true); 202 | } else if (receiveDataFormat.equals(Consts.INTEGER)) { 203 | menu.findItem(R.id.menuSettingsReceiveInteger).setChecked(true); 204 | } else if (receiveDataFormat.equals(Consts.HEXADECIMAL)) { 205 | menu.findItem(R.id.menuSettingsReceiveHexadecimal).setChecked(true); 206 | } else if (receiveDataFormat.equals(Consts.TEXT)) { 207 | menu.findItem(R.id.menuSettingsReceiveText).setChecked(true); 208 | } 209 | } 210 | 211 | setDelimiter(); 212 | if (settingsDelimiter.equals(Consts.DELIMITER_NONE)) { 213 | menu.findItem(R.id.menuSettingsDelimiterNone).setChecked(true); 214 | } else if (settingsDelimiter.equals(Consts.DELIMITER_NEW_LINE)) { 215 | menu.findItem(R.id.menuSettingsDelimiterNewLine).setChecked(true); 216 | } else if (settingsDelimiter.equals(Consts.DELIMITER_SPACE)) { 217 | menu.findItem(R.id.menuSettingsDelimiterSpace).setChecked(true); 218 | } 219 | } 220 | 221 | @Override 222 | public boolean onOptionsItemSelected(MenuItem item) { 223 | SharedPreferences.Editor editor = sharedPreferences.edit(); 224 | item.setChecked(true); 225 | switch (item.getItemId()) { 226 | case R.id.menuSettings: 227 | Intent i = new Intent(this, SettingsActivity.class); 228 | startActivityForResult(i, Consts.RESULT_SETTINGS); 229 | break; 230 | case R.id.menuSettingsReceiveBinary: 231 | editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.BINARY).apply(); 232 | break; 233 | case R.id.menuSettingsReceiveInteger: 234 | editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.INTEGER).apply(); 235 | break; 236 | case R.id.menuSettingsReceiveHexadecimal: 237 | editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.HEXADECIMAL).apply(); 238 | break; 239 | case R.id.menuSettingsReceiveText: 240 | editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT).apply(); 241 | break; 242 | case R.id.menuSettingsDelimiterNone: 243 | editor.putString(Consts.DELIMITER, Consts.DELIMITER_NONE).apply(); 244 | break; 245 | case R.id.menuSettingsDelimiterNewLine: 246 | editor.putString(Consts.DELIMITER, Consts.DELIMITER_NEW_LINE).apply(); 247 | break; 248 | case R.id.menuSettingsDelimiterSpace: 249 | editor.putString(Consts.DELIMITER, Consts.DELIMITER_SPACE).apply(); 250 | break; 251 | } 252 | 253 | receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT); 254 | setDelimiter(); 255 | return true; 256 | } 257 | 258 | @Override 259 | protected void onNewIntent(Intent intent) { 260 | super.onNewIntent(intent); 261 | String action = intent.getAction(); 262 | if (action == null) { 263 | return; 264 | } 265 | switch (action) { 266 | case Consts.WEB_SERVER_CLOSE_ACTION: 267 | stopService(new Intent(this, WebServerService.class)); 268 | break; 269 | case Consts.USB_HID_TERMINAL_CLOSE_ACTION: 270 | stopService(new Intent(this, SocketService.class)); 271 | stopService(new Intent(this, WebServerService.class)); 272 | stopService(new Intent(this, USBHIDService.class)); 273 | ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(Consts.USB_HID_TERMINAL_NOTIFICATION); 274 | finish(); 275 | break; 276 | case Consts.SOCKET_SERVER_CLOSE_ACTION: 277 | stopService(new Intent(this, SocketService.class)); 278 | sharedPreferences.edit().putBoolean("enable_socket_server", false).apply(); 279 | break; 280 | } 281 | } 282 | 283 | private void setDelimiter() { 284 | settingsDelimiter = sharedPreferences.getString(Consts.DELIMITER, Consts.DELIMITER_NEW_LINE); 285 | if (settingsDelimiter != null) { 286 | if (settingsDelimiter.equals(Consts.DELIMITER_NONE)) { 287 | delimiter = ""; 288 | } else if (settingsDelimiter.equals(Consts.DELIMITER_NEW_LINE)) { 289 | delimiter = Consts.NEW_LINE; 290 | } else if (settingsDelimiter.equals(Consts.DELIMITER_SPACE)) { 291 | delimiter = Consts.SPACE; 292 | } 293 | } 294 | usbService.setAction(Consts.RECEIVE_DATA_FORMAT); 295 | usbService.putExtra(Consts.RECEIVE_DATA_FORMAT, receiveDataFormat); 296 | usbService.putExtra(Consts.DELIMITER, delimiter); 297 | startService(usbService); 298 | } 299 | 300 | void sendToUSBService(String action) { 301 | usbService.setAction(action); 302 | startService(usbService); 303 | } 304 | 305 | void sendToUSBService(String action, boolean data) { 306 | usbService.putExtra(action, data); 307 | sendToUSBService(action); 308 | } 309 | 310 | void sendToUSBService(String action, int data) { 311 | usbService.putExtra(action, data); 312 | sendToUSBService(action); 313 | } 314 | 315 | private void mLog(String log, boolean newLine) { 316 | if (newLine) { 317 | edtlogText.append(Consts.NEW_LINE); 318 | } 319 | edtlogText.append(log); 320 | if(edtlogText.getLineCount() > 1000) { 321 | edtlogText.setText("cleared"); 322 | } 323 | } 324 | 325 | private void webServerServiceIsStart(boolean isStart) { 326 | if (isStart) { 327 | Intent webServerService = new Intent(this, WebServerService.class); 328 | webServerService.setAction("start"); 329 | webServerService.putExtra("WEB_SERVER_PORT", Integer.parseInt(sharedPreferences.getString("web_server_port", "7799"))); 330 | startService(webServerService); 331 | } else { 332 | stopService(new Intent(this, WebServerService.class)); 333 | } 334 | } 335 | 336 | private void socketServiceIsStart(boolean isStart) { 337 | if (isStart) { 338 | Intent socketServerService = new Intent(this, SocketService.class); 339 | socketServerService.setAction("start"); 340 | socketServerService.putExtra("SOCKET_PORT", Integer.parseInt(sharedPreferences.getString("socket_server_port", "7899"))); 341 | startService(socketServerService); 342 | } else { 343 | stopService(new Intent(this, SocketService.class)); 344 | } 345 | } 346 | 347 | private void setVersionToTitle() { 348 | try { 349 | this.setTitle(Consts.SPACE + this.getTitle() + Consts.SPACE + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); 350 | } catch (NameNotFoundException e) { 351 | e.printStackTrace(); 352 | } 353 | } 354 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/Consts.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core; 2 | 3 | public abstract class Consts { 4 | public static final String BINARY = "binary"; 5 | public static final String INTEGER = "integer"; 6 | public static final String HEXADECIMAL = "hexadecimal"; 7 | public static final String TEXT = "text"; 8 | 9 | public static final String ACTION_USB_PERMISSION = "com.google.android.HID.action.USB_PERMISSION"; 10 | public static final String MESSAGE_SELECT_YOUR_USB_HID_DEVICE = "Please select your USB HID device"; 11 | public static final String MESSAGE_CONNECT_YOUR_USB_HID_DEVICE = "Please connect your USB HID device"; 12 | public static final String RECEIVE_DATA_FORMAT = "receiveDataFormat"; 13 | public static final String DELIMITER = "delimiter"; 14 | public static final String DELIMITER_NONE = "none"; 15 | public static final String DELIMITER_NEW_LINE = "newLine"; 16 | public static final String DELIMITER_SPACE = "space"; 17 | public static final String NEW_LINE = "\n"; 18 | public static final String SPACE = " "; 19 | 20 | public static final String ACTION_USB_SHOW_DEVICES_LIST = "ACTION_USB_SHOW_DEVICES_LIST"; 21 | public static final String ACTION_USB_DATA_TYPE = "ACTION_USB_DATA_TYPE"; 22 | public static final int RESULT_SETTINGS = 7; 23 | public static final String USB_HID_TERMINAL_CLOSE_ACTION = "USB_HID_TERMINAL_EXIT"; 24 | public static final String WEB_SERVER_CLOSE_ACTION = "WEB_SERVER_EXIT"; 25 | public static final String SOCKET_SERVER_CLOSE_ACTION = "SOCKET_SERVER_EXIT"; 26 | public static final int USB_HID_TERMINAL_NOTIFICATION = 45277991; 27 | public static final int WEB_SERVER_NOTIFICATION = 45277992; 28 | public static final int SOCKET_SERVER_NOTIFICATION = 45277993; 29 | 30 | private Consts() { 31 | } 32 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/USBUtils.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core; 2 | 3 | public class USBUtils { 4 | 5 | public static int toInt(byte b) { 6 | return (int) b & 0xFF; 7 | } 8 | 9 | public static byte toByte(int c) { 10 | return (byte) (c <= 0x7f ? c : ((c % 0x80) - 0x80)); 11 | } 12 | 13 | public static String getIpAddress(int ipAddress) { 14 | return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/DeviceAttachedEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class DeviceAttachedEvent { 4 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/DeviceDetachedEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class DeviceDetachedEvent { 4 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/LogMessageEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class LogMessageEvent { 4 | 5 | private final String data; 6 | 7 | public LogMessageEvent(String data) { 8 | this.data = data; 9 | } 10 | 11 | public String getData() { 12 | return data; 13 | } 14 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/PrepareDevicesListEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class PrepareDevicesListEvent { 4 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/SelectDeviceEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class SelectDeviceEvent { 4 | private int device; 5 | 6 | public SelectDeviceEvent(int device) { 7 | this.device = device; 8 | } 9 | 10 | public int getDevice() { 11 | return device; 12 | } 13 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/ShowDevicesListEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class ShowDevicesListEvent { 4 | 5 | private final CharSequence devicesName[]; 6 | 7 | public ShowDevicesListEvent(CharSequence devicesName[]) { 8 | this.devicesName = devicesName; 9 | } 10 | 11 | public CharSequence[] getCharSequenceArray() { 12 | return devicesName; 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/USBDataReceiveEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class USBDataReceiveEvent { 4 | private final String data; 5 | private final int bytesCount; 6 | 7 | public USBDataReceiveEvent(String data, int bytesCount) { 8 | this.data = data; 9 | this.bytesCount = bytesCount; 10 | } 11 | 12 | public String getData() { 13 | return data; 14 | } 15 | 16 | public int getBytesCount() { 17 | return bytesCount; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/events/USBDataSendEvent.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.events; 2 | 3 | public class USBDataSendEvent { 4 | private final String data; 5 | 6 | public USBDataSendEvent(String data) { 7 | this.data = data; 8 | } 9 | 10 | public String getData() { 11 | return data; 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/services/AbstractUSBHIDService.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.services; 2 | 3 | import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; 4 | 5 | import java.util.HashMap; 6 | import java.util.Iterator; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | 10 | import android.app.PendingIntent; 11 | import android.app.Service; 12 | import android.content.BroadcastReceiver; 13 | import android.content.Context; 14 | import android.content.Intent; 15 | import android.content.IntentFilter; 16 | import android.hardware.usb.UsbConstants; 17 | import android.hardware.usb.UsbDevice; 18 | import android.hardware.usb.UsbDeviceConnection; 19 | import android.hardware.usb.UsbEndpoint; 20 | import android.hardware.usb.UsbInterface; 21 | import android.hardware.usb.UsbManager; 22 | import android.os.Build; 23 | import android.os.Handler; 24 | import android.os.IBinder; 25 | import android.util.Log; 26 | 27 | import com.appspot.usbhidterminal.core.Consts; 28 | import com.appspot.usbhidterminal.core.USBUtils; 29 | import com.appspot.usbhidterminal.core.events.PrepareDevicesListEvent; 30 | import com.appspot.usbhidterminal.core.events.SelectDeviceEvent; 31 | import com.appspot.usbhidterminal.core.events.USBDataSendEvent; 32 | 33 | import org.greenrobot.eventbus.EventBus; 34 | import org.greenrobot.eventbus.Subscribe; 35 | import org.greenrobot.eventbus.ThreadMode; 36 | 37 | public abstract class AbstractUSBHIDService extends Service { 38 | 39 | private static final String TAG = AbstractUSBHIDService.class.getCanonicalName(); 40 | 41 | public static final int REQUEST_GET_REPORT = 0x01; 42 | public static final int REQUEST_SET_REPORT = 0x09; 43 | public static final int REPORT_TYPE_INPUT = 0x0100; 44 | public static final int REPORT_TYPE_OUTPUT = 0x0200; 45 | public static final int REPORT_TYPE_FEATURE = 0x0300; 46 | 47 | private USBThreadDataReceiver usbThreadDataReceiver; 48 | 49 | private final Handler uiHandler = new Handler(); 50 | 51 | private List interfacesList = null; 52 | 53 | private UsbManager mUsbManager; 54 | private UsbDeviceConnection connection; 55 | private UsbDevice device; 56 | 57 | private IntentFilter filter; 58 | private PendingIntent mPermissionIntent; 59 | 60 | private boolean sendedDataType; 61 | 62 | protected EventBus eventBus = EventBus.getDefault(); 63 | 64 | @Override 65 | public IBinder onBind(Intent intent) { 66 | return null; 67 | } 68 | 69 | @Override 70 | public void onCreate() { 71 | super.onCreate(); 72 | mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(Consts.ACTION_USB_PERMISSION), PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT : 0)); 73 | filter = new IntentFilter(Consts.ACTION_USB_PERMISSION); 74 | filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); 75 | filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); 76 | filter.addAction(Consts.ACTION_USB_SHOW_DEVICES_LIST); 77 | filter.addAction(Consts.ACTION_USB_DATA_TYPE); 78 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 79 | registerReceiver(mUsbReceiver, filter, Context.RECEIVER_EXPORTED); 80 | } else { 81 | registerReceiver(mUsbReceiver, filter); 82 | } 83 | eventBus.register(this); 84 | } 85 | 86 | @Override 87 | public int onStartCommand(Intent intent, int flags, int startId) { 88 | String action = intent.getAction(); 89 | if (Consts.ACTION_USB_DATA_TYPE.equals(action)) { 90 | sendedDataType = intent.getBooleanExtra(Consts.ACTION_USB_DATA_TYPE, false); 91 | } 92 | onCommand(intent, action, flags, startId); 93 | return START_REDELIVER_INTENT; 94 | } 95 | 96 | @Override 97 | public void onDestroy() { 98 | eventBus.unregister(this); 99 | super.onDestroy(); 100 | if (usbThreadDataReceiver != null) { 101 | usbThreadDataReceiver.stopThis(); 102 | } 103 | unregisterReceiver(mUsbReceiver); 104 | } 105 | 106 | private class USBThreadDataReceiver extends Thread { 107 | 108 | private volatile boolean isStopped; 109 | 110 | public USBThreadDataReceiver() { 111 | } 112 | 113 | @Override 114 | public void run() { 115 | try { 116 | if (connection != null) { 117 | while (!isStopped) { 118 | for (UsbInterface intf: interfacesList) { 119 | for (int i = 0; i < intf.getEndpointCount(); i++) { 120 | UsbEndpoint endPointRead = intf.getEndpoint(i); 121 | if (UsbConstants.USB_DIR_IN == endPointRead.getDirection()) { 122 | final byte[] buffer = new byte[endPointRead.getMaxPacketSize()]; 123 | final int status = connection.bulkTransfer(endPointRead, buffer, buffer.length, 100); 124 | if (status > 0) { 125 | uiHandler.post(new Runnable() { 126 | @Override 127 | public void run() { 128 | onUSBDataReceive(buffer); 129 | } 130 | }); 131 | } else { 132 | int transfer = connection.controlTransfer(0xA0, REQUEST_GET_REPORT, REPORT_TYPE_OUTPUT, 0x00, buffer, buffer.length, 100); 133 | if (transfer > 0) { 134 | uiHandler.post(new Runnable() { 135 | @Override 136 | public void run() { 137 | onUSBDataReceive(buffer); 138 | } 139 | }); 140 | } 141 | } 142 | } 143 | } 144 | } 145 | } 146 | } 147 | } catch (Exception e) { 148 | Log.e(TAG, "Error in receive thread", e); 149 | } 150 | } 151 | 152 | public void stopThis() { 153 | isStopped = true; 154 | } 155 | } 156 | 157 | @Subscribe(threadMode = ThreadMode.MAIN) 158 | public void onEventMainThread(USBDataSendEvent event){ 159 | sendData(event.getData(), sendedDataType); 160 | } 161 | 162 | @Subscribe(threadMode = ThreadMode.MAIN) 163 | public void onEvent(SelectDeviceEvent event) { 164 | device = (UsbDevice) mUsbManager.getDeviceList().values().toArray()[event.getDevice()]; 165 | mUsbManager.requestPermission(device, mPermissionIntent); 166 | } 167 | 168 | @Subscribe(threadMode = ThreadMode.MAIN) 169 | public void onEventMainThread(PrepareDevicesListEvent event) { 170 | mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); 171 | List list = new LinkedList(); 172 | for (UsbDevice usbDevice : mUsbManager.getDeviceList().values()) { 173 | list.add(onBuildingDevicesList(usbDevice)); 174 | } 175 | final CharSequence devicesName[] = new CharSequence[mUsbManager.getDeviceList().size()]; 176 | list.toArray(devicesName); 177 | onShowDevicesList(devicesName); 178 | } 179 | 180 | private void sendData(String data, boolean sendAsString) { 181 | if (device != null && mUsbManager.hasPermission(device) && !data.isEmpty()) { 182 | // mLog(connection +"\n"+ device +"\n"+ request +"\n"+ 183 | // packetSize); 184 | for (UsbInterface intf: interfacesList) { 185 | for (int i = 0; i < intf.getEndpointCount(); i++) { 186 | UsbEndpoint endPointWrite = intf.getEndpoint(i); 187 | if (UsbConstants.USB_DIR_OUT == endPointWrite.getDirection()) { 188 | byte[] out = data.getBytes();// UTF-16LE 189 | // Charset.forName("UTF-16") 190 | onUSBDataSending(data); 191 | if (sendAsString) { 192 | try { 193 | String str[] = data.split("[\\s]"); 194 | out = new byte[str.length]; 195 | for (int s = 0; s < str.length; s++) { 196 | out[s] = USBUtils.toByte(Integer.decode(str[s])); 197 | } 198 | } catch (Exception e) { 199 | onSendingError(e); 200 | } 201 | } 202 | int status = connection.bulkTransfer(endPointWrite, out, out.length, 250); 203 | onUSBDataSended(status, out); 204 | status = connection.controlTransfer(0x21, REQUEST_SET_REPORT, REPORT_TYPE_OUTPUT, 0x02, out, out.length, 250); 205 | onUSBDataSended(status, out); 206 | } 207 | } 208 | } 209 | } 210 | } 211 | 212 | /** 213 | * receives the permission request to connect usb devices 214 | */ 215 | private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { 216 | public void onReceive(Context context, Intent intent) { 217 | String action = intent.getAction(); 218 | if (Consts.ACTION_USB_PERMISSION.equals(action)) { 219 | setDevice(intent); 220 | } 221 | if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { 222 | setDevice(intent); 223 | if (device != null) { 224 | onDeviceConnected(device); 225 | } 226 | } 227 | if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { 228 | if (device != null) { 229 | device = null; 230 | if (usbThreadDataReceiver != null) { 231 | usbThreadDataReceiver.stopThis(); 232 | } 233 | onDeviceDisconnected(device); 234 | } 235 | } 236 | } 237 | 238 | private void setDevice(Intent intent) { 239 | synchronized (this) { 240 | device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); 241 | Log.d(TAG, "Broadcast received. Device: " + device); 242 | if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) && device != null) { 243 | Log.d(TAG, "Permission granted for device: " + device.getDeviceName()); 244 | onDeviceSelected(device); 245 | connection = mUsbManager.openDevice(device); 246 | if (connection == null) { 247 | return; 248 | } 249 | interfacesList = new LinkedList<>(); 250 | for (int i = 0; i < device.getInterfaceCount(); i++) { 251 | UsbInterface intf = device.getInterface(i); 252 | connection.claimInterface(intf, true); 253 | interfacesList.add(intf); 254 | } 255 | usbThreadDataReceiver = new USBThreadDataReceiver(); 256 | usbThreadDataReceiver.start(); 257 | onDeviceAttached(device); 258 | } else { 259 | Log.e(TAG, "Permission denied for the USB HID device"); 260 | } 261 | } 262 | } 263 | }; 264 | 265 | public void onCommand(Intent intent, String action, int flags, int startId) { 266 | } 267 | 268 | public void onUSBDataReceive(byte[] buffer) { 269 | } 270 | 271 | public void onDeviceConnected(UsbDevice device) { 272 | } 273 | 274 | public void onDeviceDisconnected(UsbDevice device) { 275 | } 276 | 277 | public void onDeviceSelected(UsbDevice device) { 278 | } 279 | 280 | public void onDeviceAttached(UsbDevice device) { 281 | } 282 | 283 | public void onShowDevicesList(CharSequence[] deviceName) { 284 | } 285 | 286 | public CharSequence onBuildingDevicesList(UsbDevice usbDevice) { 287 | return null; 288 | } 289 | 290 | public void onUSBDataSending(String data) { 291 | } 292 | 293 | public void onUSBDataSended(int status, byte[] out) { 294 | } 295 | 296 | public void onSendingError(Exception e) { 297 | } 298 | 299 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/services/SocketService.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.services; 2 | 3 | import android.app.NotificationManager; 4 | import android.app.PendingIntent; 5 | import android.app.Service; 6 | import android.content.Intent; 7 | import android.net.wifi.WifiManager; 8 | import android.os.Binder; 9 | import android.os.IBinder; 10 | import android.util.Log; 11 | 12 | import androidx.core.app.NotificationCompat; 13 | 14 | import com.appspot.usbhidterminal.R; 15 | import com.appspot.usbhidterminal.USBHIDTerminal; 16 | import com.appspot.usbhidterminal.core.Consts; 17 | import com.appspot.usbhidterminal.core.USBUtils; 18 | import com.appspot.usbhidterminal.core.events.LogMessageEvent; 19 | import com.appspot.usbhidterminal.core.events.USBDataReceiveEvent; 20 | import com.appspot.usbhidterminal.core.events.USBDataSendEvent; 21 | 22 | import org.greenrobot.eventbus.EventBus; 23 | import org.greenrobot.eventbus.Subscribe; 24 | import org.greenrobot.eventbus.ThreadMode; 25 | 26 | import java.io.BufferedReader; 27 | import java.io.DataOutputStream; 28 | import java.io.IOException; 29 | import java.io.InputStreamReader; 30 | import java.net.InetSocketAddress; 31 | import java.net.ServerSocket; 32 | import java.net.Socket; 33 | import java.net.SocketException; 34 | 35 | public class SocketService extends Service { 36 | 37 | private static final String TAG = SocketService.class.getCanonicalName(); 38 | private static final int DEFAULT_SOCKET_PORT = 7899; 39 | private EventBus eventBus = EventBus.getDefault(); 40 | private int socketPort = DEFAULT_SOCKET_PORT; 41 | private SocketThreadDataReceiver socketThreadDataReceiver; 42 | private BufferedReader in; 43 | private DataOutputStream out; 44 | private ServerSocket serverSocket; 45 | private Socket socket; 46 | 47 | private final IBinder socketServiceBinder = new LocalBinder(); 48 | 49 | public SocketService() { 50 | } 51 | 52 | @Override 53 | public void onCreate() { 54 | super.onCreate(); 55 | setupNotifications(); 56 | eventBus.register(this); 57 | } 58 | 59 | @Override 60 | public void onDestroy() { 61 | try { 62 | if (socketThreadDataReceiver != null) { 63 | socketThreadDataReceiver.stopThis(); 64 | } 65 | if (socket != null) { 66 | socket.shutdownInput(); 67 | socket.shutdownOutput(); 68 | in.close(); 69 | out.close(); 70 | socket.close(); 71 | } 72 | if (serverSocket != null) { 73 | serverSocket.close(); 74 | } 75 | ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(Consts.SOCKET_SERVER_NOTIFICATION); 76 | } catch (IOException e) { 77 | Log.e(TAG, "Close streams", e); 78 | } 79 | eventBus.unregister(this); 80 | super.onDestroy(); 81 | } 82 | 83 | @Override 84 | public IBinder onBind(Intent intent) { 85 | return socketServiceBinder; 86 | } 87 | 88 | 89 | public class LocalBinder extends Binder { 90 | public SocketService getService() { 91 | return SocketService.this; 92 | } 93 | } 94 | 95 | @Override 96 | public int onStartCommand(Intent intent, int flags, int startId) { 97 | String action = intent.getAction(); 98 | if (action.equals("start")) { 99 | socketPort = intent.getIntExtra("SOCKET_PORT", DEFAULT_SOCKET_PORT); 100 | if (socketThreadDataReceiver == null) { 101 | socketThreadDataReceiver = new SocketThreadDataReceiver(); 102 | socketThreadDataReceiver.start(); 103 | WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); 104 | if (wm.isWifiEnabled()) { 105 | String ip = USBUtils.getIpAddress(wm.getConnectionInfo().getIpAddress()); 106 | EventBus.getDefault().post(new LogMessageEvent("Socket service launched\n" + 107 | "telnet " + ip + " " + socketPort)); 108 | } 109 | } 110 | } 111 | return START_REDELIVER_INTENT; 112 | } 113 | 114 | private void setup() { 115 | try { 116 | serverSocket = new ServerSocket(); 117 | serverSocket.setReuseAddress(true); 118 | serverSocket.bind(new InetSocketAddress(socketPort)); 119 | waitingForConnection(); 120 | } catch (IOException e) { 121 | Log.w(TAG, e); 122 | } 123 | } 124 | 125 | private void waitingForConnection() { 126 | try { 127 | socket = serverSocket.accept(); 128 | out = new DataOutputStream(socket.getOutputStream()); 129 | in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 130 | out.writeChars("Hello from USBHIDTerminal\n"); 131 | } catch (SocketException e) { 132 | } catch (IOException e) { 133 | Log.w(TAG, e); 134 | } 135 | } 136 | 137 | @Subscribe(threadMode = ThreadMode.MAIN) 138 | public void onEvent(USBDataReceiveEvent event) { 139 | if (socket != null && socket.isConnected()) { 140 | try { 141 | out.writeBytes(event.getData()); 142 | } catch (IOException e) { 143 | } 144 | } 145 | } 146 | 147 | private class SocketThreadDataReceiver extends Thread { 148 | 149 | private volatile boolean isStopped; 150 | 151 | public SocketThreadDataReceiver() { 152 | } 153 | 154 | @Override 155 | public void run() { 156 | try { 157 | setup(); 158 | if (socket != null && socket.isConnected()) { 159 | while (!isStopped) { 160 | String data = in.readLine(); 161 | if (data == null) { 162 | waitingForConnection(); 163 | } else { 164 | eventBus.post(new USBDataSendEvent(data)); 165 | } 166 | } 167 | } 168 | } catch (Exception e) { 169 | Log.e(TAG, "Error in receive thread", e); 170 | } 171 | } 172 | 173 | public void stopThis() { 174 | isStopped = true; 175 | } 176 | } 177 | 178 | private void setupNotifications() { //called in onCreate() 179 | NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 180 | NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this); 181 | PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 182 | new Intent(this, USBHIDTerminal.class) 183 | .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 184 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); 185 | PendingIntent pendingCloseIntent = PendingIntent.getActivity(this, 0, 186 | new Intent(this, USBHIDTerminal.class) 187 | .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP) 188 | .setAction(Consts.SOCKET_SERVER_CLOSE_ACTION), 189 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); 190 | mNotificationBuilder 191 | .setSmallIcon(R.drawable.ic_launcher) 192 | .setCategory(NotificationCompat.CATEGORY_SERVICE) 193 | .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) 194 | .setContentTitle(getText(R.string.app_name)) 195 | .setWhen(System.currentTimeMillis()) 196 | .setContentIntent(pendingIntent) 197 | .addAction(android.R.drawable.ic_menu_close_clear_cancel, 198 | getString(R.string.action_exit), pendingCloseIntent) 199 | .setOngoing(true); 200 | 201 | mNotificationBuilder 202 | .setTicker(getText(R.string.app_name)) 203 | .setContentText(getText(R.string.socket_server)); 204 | if (mNotificationManager != null) { 205 | mNotificationManager.notify(Consts.SOCKET_SERVER_NOTIFICATION, mNotificationBuilder.build()); 206 | } 207 | } 208 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/services/USBHIDService.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.services; 2 | 3 | import android.app.NotificationManager; 4 | import android.app.PendingIntent; 5 | import android.content.Intent; 6 | import android.hardware.usb.UsbConfiguration; 7 | import android.hardware.usb.UsbConstants; 8 | import android.hardware.usb.UsbDevice; 9 | import android.hardware.usb.UsbEndpoint; 10 | import android.hardware.usb.UsbInterface; 11 | 12 | import androidx.core.app.NotificationCompat; 13 | 14 | import com.appspot.usbhidterminal.R; 15 | import com.appspot.usbhidterminal.USBHIDTerminal; 16 | import com.appspot.usbhidterminal.core.Consts; 17 | import com.appspot.usbhidterminal.core.USBUtils; 18 | import com.appspot.usbhidterminal.core.events.DeviceAttachedEvent; 19 | import com.appspot.usbhidterminal.core.events.DeviceDetachedEvent; 20 | import com.appspot.usbhidterminal.core.events.LogMessageEvent; 21 | import com.appspot.usbhidterminal.core.events.ShowDevicesListEvent; 22 | import com.appspot.usbhidterminal.core.events.USBDataReceiveEvent; 23 | 24 | public class USBHIDService extends AbstractUSBHIDService { 25 | 26 | private String delimiter; 27 | private String receiveDataFormat; 28 | 29 | @Override 30 | public void onCreate() { 31 | super.onCreate(); 32 | setupNotifications(); 33 | } 34 | 35 | @Override 36 | public void onCommand(Intent intent, String action, int flags, int startId) { 37 | if (Consts.RECEIVE_DATA_FORMAT.equals(action)) { 38 | receiveDataFormat = intent.getStringExtra(Consts.RECEIVE_DATA_FORMAT); 39 | delimiter = intent.getStringExtra(Consts.DELIMITER); 40 | } 41 | super.onCommand(intent, action, flags, startId); 42 | } 43 | 44 | @Override 45 | public void onDestroy() { 46 | super.onDestroy(); 47 | } 48 | 49 | @Override 50 | public void onDeviceConnected(UsbDevice device) { 51 | mLog("device VID:0x" + Integer.toHexString(device.getVendorId()) + " PID:0x" + Integer.toHexString(device.getProductId()) + " " + device.getDeviceName() + " connected"); 52 | } 53 | 54 | @Override 55 | public void onDeviceDisconnected(UsbDevice device) { 56 | mLog("device disconnected"); 57 | eventBus.post(new DeviceDetachedEvent()); 58 | } 59 | 60 | @Override 61 | public void onDeviceSelected(UsbDevice device) { 62 | mLog("Selected device VID:0x" + Integer.toHexString(device.getVendorId()) + " PID:0x" + Integer.toHexString(device.getProductId())); 63 | mLog("id " + showDecHex(device.getDeviceId())); 64 | mLog("name " + device.getDeviceName()); 65 | mLog("manufacturer name " + device.getManufacturerName()); 66 | mLog("serial number " + device.getSerialNumber()); 67 | mLog("class " + showDecHex(device.getDeviceClass())); 68 | mLog("subclass " + showDecHex(device.getDeviceSubclass())); 69 | mLog("protocol " + showDecHex(device.getDeviceProtocol())); 70 | mLog(""); 71 | mLog("interfaces count " + device.getInterfaceCount()); 72 | for (int i = 0; i < device.getInterfaceCount(); i++) { 73 | mLog(""); 74 | mLog("interface " + i); 75 | UsbInterface dInterface = device.getInterface(i); 76 | mLog(" name " + dInterface.getName()); 77 | mLog(" id " + showDecHex(dInterface.getId())); 78 | mLog(" class " + showDecHex(dInterface.getInterfaceClass())); 79 | mLog(" subclass " + showDecHex(dInterface.getInterfaceSubclass())); 80 | mLog(" protocol " + showDecHex(dInterface.getInterfaceProtocol())); 81 | mLog(""); 82 | mLog(" endpoint count " + dInterface.getEndpointCount()); 83 | for (int ien = 0; ien < dInterface.getEndpointCount(); ien++) { 84 | UsbEndpoint endpoint = dInterface.getEndpoint(ien); 85 | mLog(""); 86 | mLog(" endpoint " + ien); 87 | mLog(" endpoint number " + endpoint.getEndpointNumber()); 88 | mLog(" address " + showDecHex(endpoint.getAddress())); 89 | mLog(" type " + showDecHex(endpoint.getType())); 90 | mLog(" direction " + directionInfo(endpoint.getDirection())); 91 | mLog(" max packet size " + endpoint.getMaxPacketSize()); 92 | mLog(" interval " + endpoint.getInterval()); 93 | mLog(" attributes " + showDecHex(endpoint.getAttributes())); 94 | } 95 | } 96 | mLog(""); 97 | mLog("configuration count " + device.getConfigurationCount()); 98 | for (int i = 0; i < device.getConfigurationCount(); i++) { 99 | UsbConfiguration configuration = device.getConfiguration(i); 100 | mLog(""); 101 | mLog("configuration " + i); 102 | mLog(" name " + configuration.getName()); 103 | mLog(" id " + showDecHex(configuration.getId())); 104 | mLog(" max power " + configuration.getMaxPower()); 105 | mLog(" is self powered " + configuration.isSelfPowered()); 106 | mLog(""); 107 | mLog("configuration interfaces count " + configuration.getInterfaceCount()); 108 | for (int ic = 0; i < configuration.getInterfaceCount(); i++) { 109 | mLog(""); 110 | mLog("configuration interface " + ic); 111 | UsbInterface cInterface = configuration.getInterface(i); 112 | mLog(" name " + cInterface.getName()); 113 | mLog(" id " + showDecHex(cInterface.getId())); 114 | mLog(" class " + showDecHex(cInterface.getInterfaceClass())); 115 | mLog(" subclass " + showDecHex(cInterface.getInterfaceSubclass())); 116 | mLog(" protocol " + showDecHex(cInterface.getInterfaceProtocol())); 117 | mLog(""); 118 | mLog(" configuration endpoint count " + cInterface.getEndpointCount()); 119 | for (int ien = 0; ien < cInterface.getEndpointCount(); ien++) { 120 | UsbEndpoint endpoint = cInterface.getEndpoint(ien); 121 | mLog(""); 122 | mLog(" endpoint " + ien); 123 | mLog(" endpoint number " + endpoint.getEndpointNumber()); 124 | mLog(" address " + showDecHex(endpoint.getAddress())); 125 | mLog(" type " + showDecHex(endpoint.getType())); 126 | mLog(" direction " + directionInfo(endpoint.getDirection())); 127 | mLog(" max packet size " + endpoint.getMaxPacketSize()); 128 | mLog(" interval " + endpoint.getInterval()); 129 | mLog(" attributes " + showDecHex(endpoint.getAttributes())); 130 | } 131 | } 132 | } 133 | 134 | } 135 | 136 | @Override 137 | public void onDeviceAttached(UsbDevice device) { 138 | eventBus.post(new DeviceAttachedEvent()); 139 | } 140 | 141 | @Override 142 | public void onShowDevicesList(CharSequence[] deviceName) { 143 | eventBus.post(new ShowDevicesListEvent(deviceName)); 144 | } 145 | 146 | private String directionInfo(int data) { 147 | if (UsbConstants.USB_DIR_IN == data) { 148 | return "IN " + showDecHex(data); 149 | } 150 | if (UsbConstants.USB_DIR_OUT == data) { 151 | return "OUT " + showDecHex(data); 152 | } 153 | return "NA " + showDecHex(data); 154 | } 155 | 156 | private String showDecHex(int data) { 157 | return data + " 0x" + Integer.toHexString(data); 158 | } 159 | 160 | @Override 161 | public CharSequence onBuildingDevicesList(UsbDevice usbDevice) { 162 | return "VID:0x" + Integer.toHexString(usbDevice.getVendorId()) + " PID:0x" + Integer.toHexString(usbDevice.getProductId()) + " " + usbDevice.getDeviceName() + " devID:" + usbDevice.getDeviceId(); 163 | } 164 | 165 | @Override 166 | public void onUSBDataSending(String data) { 167 | mLog("Sending: " + data); 168 | } 169 | 170 | @Override 171 | public void onUSBDataSended(int status, byte[] out) { 172 | if (status <= 0) { 173 | mLog("Unable to send"); 174 | } else { 175 | mLog("Sended " + status + " bytes"); 176 | for (int i = 0; i < out.length/* && out[i] != 0*/; i++) { 177 | mLog(Consts.SPACE + USBUtils.toInt(out[i])); 178 | } 179 | } 180 | } 181 | 182 | @Override 183 | public void onSendingError(Exception e) { 184 | mLog("Please check your bytes, sent as text"); 185 | } 186 | 187 | @Override 188 | public void onUSBDataReceive(byte[] buffer) { 189 | 190 | StringBuilder stringBuilder = new StringBuilder(); 191 | int i = 0; 192 | if (receiveDataFormat.equals(Consts.INTEGER)) { 193 | for (; i < buffer.length/* && buffer[i] != 0*/; i++) { 194 | stringBuilder.append(delimiter).append(String.valueOf(USBUtils.toInt(buffer[i]))); 195 | } 196 | } else if (receiveDataFormat.equals(Consts.HEXADECIMAL)) { 197 | for (; i < buffer.length/* && buffer[i] != 0*/; i++) { 198 | stringBuilder.append(delimiter).append(Integer.toHexString(buffer[i])); 199 | } 200 | } else if (receiveDataFormat.equals(Consts.TEXT)) { 201 | for (; i < buffer.length/* && buffer[i] != 0*/; i++) { 202 | stringBuilder.append(String.valueOf((char) buffer[i])); 203 | } 204 | } else if (receiveDataFormat.equals(Consts.BINARY)) { 205 | for (; i < buffer.length/* && buffer[i] != 0*/; i++) { 206 | stringBuilder.append(delimiter).append("0b").append(Integer.toBinaryString(Integer.valueOf(buffer[i]))); 207 | } 208 | } 209 | eventBus.post(new USBDataReceiveEvent(stringBuilder.toString(), i)); 210 | } 211 | 212 | private void mLog(String log) { 213 | eventBus.post(new LogMessageEvent(log)); 214 | } 215 | 216 | private void setupNotifications() { //called in onCreate() 217 | NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 218 | NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this); 219 | PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 220 | new Intent(this, USBHIDTerminal.class) 221 | .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 222 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); 223 | PendingIntent pendingCloseIntent = PendingIntent.getActivity(this, 0, 224 | new Intent(this, USBHIDTerminal.class) 225 | .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP) 226 | .setAction(Consts.USB_HID_TERMINAL_CLOSE_ACTION), 227 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); 228 | mNotificationBuilder 229 | .setSmallIcon(R.drawable.ic_launcher) 230 | .setCategory(NotificationCompat.CATEGORY_SERVICE) 231 | .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) 232 | .setContentTitle(getText(R.string.app_name)) 233 | .setWhen(System.currentTimeMillis()) 234 | .setContentIntent(pendingIntent) 235 | .addAction(android.R.drawable.ic_menu_close_clear_cancel, 236 | getString(R.string.action_exit), pendingCloseIntent) 237 | .setOngoing(true); 238 | mNotificationBuilder 239 | .setTicker(getText(R.string.app_name)) 240 | .setContentText(getText(R.string.app_name)); 241 | if (mNotificationManager != null) { 242 | mNotificationManager.notify(Consts.USB_HID_TERMINAL_NOTIFICATION, mNotificationBuilder.build()); 243 | } 244 | } 245 | 246 | } 247 | -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/services/WebServerService.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.services; 2 | 3 | import android.app.NotificationManager; 4 | import android.app.PendingIntent; 5 | import android.app.Service; 6 | import android.content.Intent; 7 | import android.net.wifi.WifiManager; 8 | import android.os.Binder; 9 | import android.os.IBinder; 10 | import androidx.core.app.NotificationCompat; 11 | 12 | import android.util.Log; 13 | 14 | import com.appspot.usbhidterminal.R; 15 | import com.appspot.usbhidterminal.USBHIDTerminal; 16 | import com.appspot.usbhidterminal.core.Consts; 17 | import com.appspot.usbhidterminal.core.USBUtils; 18 | import com.appspot.usbhidterminal.core.events.LogMessageEvent; 19 | import com.appspot.usbhidterminal.core.webserver.WebServer; 20 | 21 | import org.greenrobot.eventbus.EventBus; 22 | 23 | import java.io.IOException; 24 | 25 | public class WebServerService extends Service { 26 | 27 | private static final String TAG = WebServerService.class.getCanonicalName(); 28 | private static final int DEFAULT_WEB_SERVER_PORT = 7799; 29 | private final IBinder webServerServiceBinder = new LocalBinder(); 30 | private WebServer webServer; 31 | 32 | public WebServerService() { 33 | } 34 | 35 | @Override 36 | public IBinder onBind(Intent intent) { 37 | return webServerServiceBinder; 38 | } 39 | 40 | 41 | public class LocalBinder extends Binder { 42 | public WebServerService getService() { 43 | return WebServerService.this; 44 | } 45 | } 46 | 47 | @Override 48 | public int onStartCommand(Intent intent, int flags, int startId) { 49 | String action = intent.getAction(); 50 | if (action.equals("start")) { 51 | try { 52 | int serverPort = intent.getIntExtra("WEB_SERVER_PORT", DEFAULT_WEB_SERVER_PORT); 53 | if (webServer == null) { 54 | webServer = new WebServer(this.getAssets(), serverPort); 55 | webServer.start(); 56 | WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); 57 | if (wm.isWifiEnabled()) { 58 | String ip = USBUtils.getIpAddress(wm.getConnectionInfo().getIpAddress()); 59 | EventBus.getDefault().post(new LogMessageEvent("Web service launched\n" + 60 | "http://" + ip + ":" + serverPort + 61 | "\nws://" + ip + ":" + serverPort + "/websocket")); 62 | } 63 | } 64 | } catch (IOException e) { 65 | Log.e(TAG, "Starting Web Server error", e); 66 | EventBus.getDefault().post(new LogMessageEvent("Web service problem: " + e.getMessage())); 67 | } 68 | } 69 | return START_REDELIVER_INTENT; 70 | } 71 | 72 | @Override 73 | public void onCreate() { 74 | super.onCreate(); 75 | setupNotifications(); 76 | } 77 | 78 | @Override 79 | public void onDestroy() { 80 | if (webServer != null) { 81 | webServer.stop(); 82 | ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(Consts.WEB_SERVER_NOTIFICATION); 83 | } 84 | } 85 | 86 | private void setupNotifications() { //called in onCreate() 87 | NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 88 | NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this); 89 | PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 90 | new Intent(this, USBHIDTerminal.class) 91 | .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 92 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); 93 | PendingIntent pendingCloseIntent = PendingIntent.getActivity(this, 0, 94 | new Intent(this, USBHIDTerminal.class) 95 | .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP) 96 | .setAction(Consts.WEB_SERVER_CLOSE_ACTION), 97 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); 98 | mNotificationBuilder 99 | .setSmallIcon(R.drawable.ic_launcher) 100 | .setCategory(NotificationCompat.CATEGORY_SERVICE) 101 | .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) 102 | .setContentTitle(getText(R.string.app_name)) 103 | .setWhen(System.currentTimeMillis()) 104 | .setContentIntent(pendingIntent) 105 | .addAction(android.R.drawable.ic_menu_close_clear_cancel, 106 | getString(R.string.action_exit), pendingCloseIntent) 107 | .setOngoing(true); 108 | 109 | mNotificationBuilder 110 | .setTicker(getText(R.string.app_name)) 111 | .setContentText(getText(R.string.web_server)); 112 | if (mNotificationManager != null) { 113 | mNotificationManager.notify(Consts.WEB_SERVER_NOTIFICATION, mNotificationBuilder.build()); 114 | } 115 | } 116 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/webserver/WebServer.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.webserver; 2 | 3 | import android.content.res.AssetManager; 4 | import android.util.Log; 5 | 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | 9 | import fi.iki.elonen.IWebSocketFactory; 10 | import fi.iki.elonen.NanoHTTPD; 11 | import fi.iki.elonen.WebSocket; 12 | import fi.iki.elonen.WebSocketResponseHandler; 13 | 14 | public class WebServer extends NanoHTTPD { 15 | 16 | private static final String TAG = WebServer.class.getCanonicalName(); 17 | private static final String MIME_JAVASCRIPT = "text/javascript"; 18 | private static final String MIME_CSS = "text/css"; 19 | private static final String MIME_JPEG = "image/jpeg"; 20 | private static final String MIME_PNG = "image/png"; 21 | private static final String MIME_SVG = "image/svg+xml"; 22 | private static final String MIME_JSON = "application/json"; 23 | private AssetManager assetManager; 24 | private WebSocketResponseHandler responseHandler; 25 | 26 | public WebServer(AssetManager assetManager, int port) { 27 | super(port); 28 | this.assetManager = assetManager; 29 | responseHandler = new WebSocketResponseHandler(webSocketFactory); 30 | } 31 | 32 | @Override 33 | public Response serve(IHTTPSession session) { 34 | String mimeType = NanoHTTPD.MIME_HTML; 35 | String uri = session.getUri(); 36 | Response response = new Response("Sample"); 37 | if (uri.equals("/websocket")) { 38 | response = responseHandler.serve(session); 39 | } else { 40 | switch (uri) { 41 | case "/": 42 | uri = "/index.html"; 43 | break; 44 | } 45 | if (uri.endsWith(".js")) { 46 | mimeType = MIME_JAVASCRIPT; 47 | } else if (uri.endsWith(".css")) { 48 | mimeType = MIME_CSS; 49 | } else if (uri.endsWith(".html")) { 50 | mimeType = MIME_HTML; 51 | } else if (uri.endsWith(".jpeg")) { 52 | mimeType = MIME_JPEG; 53 | } else if (uri.endsWith(".png")) { 54 | mimeType = MIME_PNG; 55 | } else if (uri.endsWith(".jpg")) { 56 | mimeType = MIME_JPEG; 57 | } else if (uri.endsWith(".svg")) { 58 | mimeType = MIME_SVG; 59 | } else if (uri.endsWith(".json")) { 60 | mimeType = MIME_JSON; 61 | } 62 | response.setMimeType(mimeType); 63 | response.setData(openPage(uri)); 64 | } 65 | return response; 66 | } 67 | 68 | public void stop(){ 69 | super.stop(); 70 | } 71 | 72 | private InputStream openPage(String file) { 73 | InputStream is; 74 | try { 75 | is = open(file); 76 | } catch (IOException e) { 77 | is = openPage("/404.html"); 78 | Log.w(TAG, e); 79 | } 80 | return is; 81 | } 82 | 83 | private InputStream open(String file) throws IOException { 84 | return assetManager.open("webserver"+file); 85 | } 86 | 87 | IWebSocketFactory webSocketFactory = new IWebSocketFactory() { 88 | 89 | @Override 90 | public WebSocket openWebSocket(IHTTPSession handshake) { 91 | return new Ws(handshake); 92 | } 93 | }; 94 | 95 | } -------------------------------------------------------------------------------- /src/com/appspot/usbhidterminal/core/webserver/Ws.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.core.webserver; 2 | 3 | import android.util.Log; 4 | 5 | import com.appspot.usbhidterminal.core.events.USBDataReceiveEvent; 6 | import com.appspot.usbhidterminal.core.events.USBDataSendEvent; 7 | 8 | import org.greenrobot.eventbus.EventBus; 9 | import org.greenrobot.eventbus.Subscribe; 10 | import org.greenrobot.eventbus.ThreadMode; 11 | 12 | import java.io.IOException; 13 | import java.util.Timer; 14 | import java.util.TimerTask; 15 | 16 | 17 | import fi.iki.elonen.NanoHTTPD; 18 | import fi.iki.elonen.WebSocket; 19 | import fi.iki.elonen.WebSocketFrame; 20 | 21 | public class Ws extends WebSocket { 22 | 23 | private static final String TAG = Ws.class.getCanonicalName(); 24 | 25 | private EventBus eventBus = EventBus.getDefault(); 26 | private NanoHTTPD.IHTTPSession httpSession; 27 | private TimerTask pingTimer; 28 | 29 | public Ws(NanoHTTPD.IHTTPSession handshakeRequest) { 30 | super(handshakeRequest); 31 | this.httpSession = handshakeRequest; 32 | eventBus.register(this); 33 | 34 | // prevent connection from being closed due to inactivity: 35 | // send ping messages every 2 seconds, and the client will respond with pong 36 | pingTimer = new TimerTask() { 37 | @Override 38 | public void run(){ 39 | try { 40 | ping(new byte[0]); 41 | } catch (IOException e) { 42 | pingTimer.cancel(); 43 | } 44 | } 45 | }; 46 | new Timer().schedule(pingTimer, 1000, 2000); 47 | } 48 | 49 | @Override 50 | protected void onPong(WebSocketFrame pongFrame) { 51 | } 52 | 53 | @Override 54 | protected void onMessage(WebSocketFrame messageFrame) { 55 | EventBus.getDefault().post(new USBDataSendEvent(messageFrame.getTextPayload())); 56 | } 57 | 58 | @Override 59 | protected void onClose(WebSocketFrame.CloseCode code, String reason, 60 | boolean initiatedByRemote) { 61 | pingTimer.cancel(); 62 | eventBus.unregister(this); 63 | } 64 | 65 | @Override 66 | protected void onException(IOException e) { 67 | } 68 | 69 | @Subscribe(threadMode = ThreadMode.ASYNC) 70 | public void onEvent(USBDataReceiveEvent event) { 71 | wsSend(event.getData()); 72 | } 73 | 74 | private void wsSend(String data){ 75 | try { 76 | this.send(data); 77 | } catch (IOException e) { 78 | Log.e(TAG, "WebSocket event send error", e); 79 | } 80 | } 81 | 82 | } -------------------------------------------------------------------------------- /tests/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | -------------------------------------------------------------------------------- /tests/src/com/appspot/usbhidterminal/tests/SocketServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.tests; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | 5 | import android.content.Intent; 6 | 7 | import androidx.test.rule.ActivityTestRule; 8 | 9 | import com.appspot.usbhidterminal.USBHIDTerminal; 10 | import com.appspot.usbhidterminal.core.services.SocketService; 11 | 12 | import org.junit.Test; 13 | 14 | public class SocketServiceTest extends ActivityTestRule { 15 | 16 | public SocketServiceTest(){ 17 | super(USBHIDTerminal.class); 18 | } 19 | 20 | @Test 21 | public void test() { 22 | System.out.println("Start tst"); 23 | Intent socketService = new Intent(super.getActivity(), SocketService.class); 24 | socketService.setAction("ABCD"); 25 | super.getActivity().startService(socketService); 26 | for (int i = 0; i < 1; i++) { 27 | //send("ABCD " + i); 28 | } 29 | assertNotNull("Socket service is null", socketService); 30 | } 31 | 32 | private void send(String data){ 33 | Intent socketService = new Intent(super.getActivity(), SocketService.class); 34 | socketService.setAction(data); 35 | super.getActivity().startService(socketService); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /tests/src/com/appspot/usbhidterminal/tests/UITest.java: -------------------------------------------------------------------------------- 1 | package com.appspot.usbhidterminal.tests; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | import static org.junit.Assert.assertNull; 5 | 6 | import androidx.test.rule.ActivityTestRule; 7 | 8 | import com.appspot.usbhidterminal.USBHIDTerminal; 9 | 10 | import org.junit.Test; 11 | 12 | public class UITest extends ActivityTestRule { 13 | 14 | public UITest(){ 15 | super(USBHIDTerminal.class); 16 | } 17 | 18 | @Test 19 | public void test() { 20 | //fail("Not yet implemented"); 21 | assertNull("ReceiverActivity is null", null); 22 | } 23 | 24 | } 25 | --------------------------------------------------------------------------------