├── .gitattributes ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── UsbSerialExampleApp ├── AndroidManifest.xml ├── Assets │ └── AboutAssets.txt ├── GettingStarted.Xamarin ├── MainActivity.cs ├── Resources │ ├── AboutResources.txt │ ├── drawable │ │ └── Icon.png │ ├── layout │ │ ├── Main.axml │ │ └── serial_console.axml │ ├── values │ │ └── Strings.xml │ └── xml │ │ └── device_filter.xml ├── SerialConsoleActivity.cs └── UsbSerialExampleApp.csproj ├── UsbSerialForAndroid.sln ├── UsbSerialForAndroid ├── Extensions │ ├── AsyncExtensions.cs │ ├── BufferExtensions.cs │ ├── EventHandlerExtensions.cs │ ├── SerialDataReceivedArgs.cs │ ├── SerialInputOutputManager.cs │ ├── UsbManagerExtensions.cs │ └── UsbSerialPortInfo.cs ├── Resources │ ├── AboutResources.txt │ └── Values │ │ └── Strings.xml ├── UsbSerialForAndroid.csproj ├── Util │ └── HexDump.cs └── driver │ ├── CdcAcmSerialDriver.cs │ ├── Ch34xSerialDriver.cs │ ├── CommonUsbSerialPort.cs │ ├── Cp21xxSerialDriver.cs │ ├── FtdiSerialDriver.cs │ ├── Parity.cs │ ├── ProbeTable.cs │ ├── ProlificSerialDriver.cs │ ├── STM32SerialDriver.cs │ ├── UsbId.cs │ ├── UsbSerialDriver.cs │ ├── UsbSerialPort.cs │ ├── UsbSerialProber.cs │ ├── UsbSerialRuntimeException.cs │ └── UsbSupport.cs └── azure-pipelines.yml /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Microsoft Azure ApplicationInsights config file 170 | ApplicationInsights.config 171 | 172 | # Windows Store app package directory 173 | AppPackages/ 174 | BundleArtifacts/ 175 | 176 | # Visual Studio cache files 177 | # files ending in .cache can be ignored 178 | *.[Cc]ache 179 | # but keep track of directories ending in .cache 180 | !*.[Cc]ache/ 181 | 182 | # Others 183 | ClientBin/ 184 | [Ss]tyle[Cc]op.* 185 | ~$* 186 | *~ 187 | *.dbmdl 188 | *.dbproj.schemaview 189 | *.pfx 190 | *.publishsettings 191 | node_modules/ 192 | orleans.codegen.cs 193 | 194 | # RIA/Silverlight projects 195 | Generated_Code/ 196 | 197 | # Backup & report files from converting an old project file 198 | # to a newer Visual Studio version. Backup files are not needed, 199 | # because we have git ;-) 200 | _UpgradeReport_Files/ 201 | Backup*/ 202 | UpgradeLog*.XML 203 | UpgradeLog*.htm 204 | 205 | # SQL Server files 206 | *.mdf 207 | *.ldf 208 | 209 | # Business Intelligence projects 210 | *.rdl.data 211 | *.bim.layout 212 | *.bim_*.settings 213 | 214 | # Microsoft Fakes 215 | FakesAssemblies/ 216 | 217 | # GhostDoc plugin setting file 218 | *.GhostDoc.xml 219 | 220 | # Node.js Tools for Visual Studio 221 | .ntvs_analysis.dat 222 | 223 | # Visual Studio 6 build log 224 | *.plg 225 | 226 | # Visual Studio 6 workspace options file 227 | *.opt 228 | 229 | # Visual Studio LightSwitch build output 230 | **/*.HTMLClient/GeneratedArtifacts 231 | **/*.DesktopClient/GeneratedArtifacts 232 | **/*.DesktopClient/ModelManifest.xml 233 | **/*.Server/GeneratedArtifacts 234 | **/*.Server/ModelManifest.xml 235 | _Pvt_Extensions 236 | 237 | # LightSwitch generated files 238 | GeneratedArtifacts/ 239 | ModelManifest.xml 240 | 241 | # Paket dependency manager 242 | .paket/paket.exe 243 | 244 | # FAKE - F# Make 245 | .fake/ 246 | 247 | #Zip files 248 | *.zip -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | We are using [Contributor Covenant v2.0](https://contributor-covenant.org/version/2/0/code_of_conduct) as the code of conduct for this library. The full text is included [below](#contributor-covenant-code-of-conduct) in English, and translations are available from the Contributor Covenant organisation: 4 | 5 | * [contributor-covenant.org/translations](https://www.contributor-covenant.org/translations) 6 | * [github.com/ContributorCovenant](https://github.com/ContributorCovenant/contributor_covenant/tree/release/content/version/2/0) 7 | 8 | ## Contributor Covenant Code of Conduct 9 | 10 | ### Our Pledge 11 | 12 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 13 | 14 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 15 | 16 | ### Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 31 | * Trolling, insulting or derogatory comments, and personal or political attacks 32 | * Public or private harassment 33 | * Publishing others' private information, such as a physical or email address, without their explicit permission 34 | * Other conduct which could reasonably be considered inappropriate in a 35 | professional setting 36 | 37 | ### Enforcement Responsibilities 38 | 39 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 40 | 41 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 42 | 43 | ### Scope 44 | 45 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 46 | 47 | ### Enforcement 48 | 49 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 50 | reported to the community leaders responsible for enforcement at 51 | [coc@electronjs.org](mailto:coc@electronjs.org). 52 | All complaints will be reviewed and investigated promptly and fairly. 53 | 54 | All community leaders are obligated to respect the privacy and security of the 55 | reporter of any incident. 56 | 57 | ### Enforcement Guidelines 58 | 59 | Community leaders will follow these Community Impact Guidelines in determining 60 | the consequences for any action they deem in violation of this Code of Conduct: 61 | 62 | #### 1. Correction 63 | 64 | **Community Impact**: Use of inappropriate language or other behavior deemed 65 | unprofessional or unwelcome in the community. 66 | 67 | **Consequence**: A private, written warning from community leaders, providing 68 | clarity around the nature of the violation and an explanation of why the 69 | behavior was inappropriate. A public apology may be requested. 70 | 71 | #### 2. Warning 72 | 73 | **Community Impact**: A violation through a single incident or series 74 | of actions. 75 | 76 | **Consequence**: A warning with consequences for continued behavior. No 77 | interaction with the people involved, including unsolicited interaction with 78 | those enforcing the Code of Conduct, for a specified period of time. This 79 | includes avoiding interactions in community spaces as well as external channels 80 | like social media. Violating these terms may lead to a temporary or 81 | permanent ban. 82 | 83 | #### 3. Temporary Ban 84 | 85 | **Community Impact**: A serious violation of community standards, including 86 | sustained inappropriate behavior. 87 | 88 | **Consequence**: A temporary ban from any sort of interaction or public 89 | communication with the community for a specified period of time. No public or 90 | private interaction with the people involved, including unsolicited interaction 91 | with those enforcing the Code of Conduct, is allowed during this period. 92 | Violating these terms may lead to a permanent ban. 93 | 94 | #### 4. Permanent Ban 95 | 96 | **Community Impact**: Demonstrating a pattern of violation of community 97 | standards, including sustained inappropriate behavior, harassment of an 98 | individual, or aggression toward or disparagement of classes of individuals. 99 | 100 | **Consequence**: A permanent ban from any sort of public interaction within 101 | the community. 102 | 103 | ### Attribution 104 | 105 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 106 | version 2.0, available at 107 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 108 | 109 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 110 | enforcement ladder](https://github.com/mozilla/diversity). 111 | 112 | [homepage]: https://www.contributor-covenant.org 113 | 114 | For answers to common questions about this code of conduct, see the FAQ at 115 | https://www.contributor-covenant.org/faq. Translations are available at 116 | https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to UsbSerialForAndroid 2 | 3 | :+1::tada: First off, thanks for taking the time to contribute! :tada::+1: 4 | 5 | This library adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). 6 | By participating, you are expected to uphold this code. 7 | 8 | The following is a set of guidelines for contributing to UsbSerialForAndroid. 9 | 10 | These are just guidelines, not rules, use your best judgment and feel free to propose changes to this document in a pull request. 11 | 12 | This contribution guide was based on one used by the [Electron](https://github.com/electron/electron) project. 13 | 14 | ## [Issues](https://github.com/anotherlab/UsbSerialForAndroid/issues) 15 | 16 | Issues are created [here](https://github.com/anotherlab/UsbSerialForAndroid/issues/new). 17 | 18 | The three most important pieces of information needed to evaluate the report are a description of the bug, the hardware used, and a simple test case to recreate it. It is easier to fix a bug if it can be reproduced. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/minimal-reproducible-example). 19 | 20 | We will do our best to repond to reported issues that provide information that we can help with. This is not a commercial product and we make no claims or offers to provide any support whatsoever. 21 | 22 | If you have a code fix or suggestion, we are only looking at changes submitted as pull requests. 23 | 24 | 25 | ### Issue Closure 26 | 27 | Bug reports will be closed if no details are included. If you create an issue for an error and only provide a stack trace, it will be closed. 28 | 29 | Issues without a response from the original poster will be closed after 6 months. 30 | 31 | _If an issue has been closed and you still feel it's relevant, feel free to add a comment!_ 32 | 33 | ### Languages 34 | 35 | We accept issues in _any_ language. But the maintainers only read English. 36 | When an issue is posted in a language besides English, it is acceptable and encouraged to post an English-translated copy as a reply. 37 | Anyone may post the translated reply. 38 | In most cases, a quick pass through translation software is sufficient. 39 | Having the original text _as well as_ the translation can help mitigate translation errors. 40 | 41 | Responses to posted issues may or may not be in the original language. 42 | 43 | **Please note** that using non-English as an attempt to circumvent our [Code of Conduct](https://github.com/anotherlab/UsbSerialForAndroid/blob/main/CODE_OF_CONDUCT.md) will be an immediate, and possibly indefinite, ban from the project. 44 | 45 | ## [Pull Requests](https://github.com/anotherlab/UsbSerialForAndroid/pulls) 46 | 47 | We welcome Pull Requests to fix or add features. This is a community project and we do not have access to every USB to Serial adapter or every serial device. 48 | 49 | * Step 1: Fork this repository 50 | * Step 2: Build it 51 | * Step 3: Make a branch 52 | * Step 4: Make changes and test the changes on actual hardware 53 | * Step 5: Commit the changes to your forked copy of the repository 54 | * Step 6: Rebase to stay in synch 55 | * Step 7: Push your commits to your forked branch 56 | * Step 8: Open the Pull Request 57 | 58 | Your Pull Request will need to document the changes and the hardware that it was tested on. 59 | 60 | ## Style Guides 61 | 62 | See the DotNet Runtime [Coding Style](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md) for information about which standards we try to adhere to. 63 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2011-2017 Google Inc. 4 | Copyright (c) 2017 Tyler Technologies 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UsbSerialForAndroid 2 | 3 | This is a driver library to allow your Xamarin Android or Microsoft Android app to communicate with many common USB serial hardware. It uses the [Android USB Host API](http://developer.android.com/guide/topics/connectivity/usb/host.html) 4 | available on Android 3.1+. 5 | 6 | No root access, ADK, or special kernel drivers are required; all drivers are implemented in 7 | c#. You get a raw serial port with `Read()`, `Write()`, and other basic 8 | functions for use with your own protocols. The appropriate driver is picked based on the device's Vendor ID and Product ID. 9 | 10 | This is a Xamarin C# port of Mike Wakerly's Java [usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) library. It followed that library very closely when it was ported. The main changes were to make the method names follow C# standard naming conventions. Some Java specific data types were replaced with .NET types and the reflection code is .NET specific. Code examples written for the Java version of the library should translate more or less faithfully to C#. 11 | 12 | It also includes code derived from a portion of LusoVU's [XamarinUsbSerial](https://bitbucket.org/lusovu/xamarinusbserial) library. XamarinUsbSerial was a C# wrapper for the Java usb-serial-for-android. It used an older version of the usb-serial-for-android .jar file. Only the the C# code was used, the Java library is not referenced. 13 | 14 | The default branch has been renamed from master to main. if you have a local clone, you can run the following commands to update the name of the default branch 15 | 16 | ``` 17 | git branch -m master main 18 | git fetch origin 19 | git branch -u origin/main main 20 | git remote set-head origin -a 21 | ``` 22 | 23 | This library currently supports Xamarin.Android, .NET 6, .NET 7, and .NET 8. The demo app currently targets .NET 8, but the code was written for Xamarin.Android. The code works with .NET 9 and an upcoming update will update the demo projects to .NET 9. 24 | 25 | Support for Xamarin will be dropped in the next update. Microsoft has ended support for Xamarin and you can no longer support apps to the Google Play Store that were built with Xamarin. 26 | 27 | ## Structure 28 | 29 | This solution contains two projects. 30 | 31 | * UsbSerialForAndroid - A port of the Java library usb-serial-for-android 32 | * UsbSerialExampleApp - A Xamarin version of the example app that comes with usb-serial-for-android 33 | 34 | ## Getting Started 35 | **1.** Reference the library to your project 36 | 37 | **2.** Copy the [device_filter.axml](https://github.com/anotherlab/UsbSerialForAndroid/blob/master/UsbSerialExampleApp/Resources/xml/device_filter.xml) from the example app to your Resources/xml folder. Make sure that the Build Action is set to AndroidResource 38 | 39 | **3.** Add the following attribute to the main activity to enable the USB Host 40 | ```C# 41 | [assembly: UsesFeature("android.hardware.usb.host")] 42 | ``` 43 | 44 | **4.** Add the following IntentFilter to the main activity to receive USB device attached notifications 45 | ```C# 46 | [IntentFilter(new[] { UsbManager.ActionUsbDeviceAttached })] 47 | ``` 48 | 49 | **5.** Add the MetaData attribute to associate the device_filter with the USB attached event to only see the devices that we are looking for 50 | ```C# 51 | [MetaData(UsbManager.ActionUsbDeviceAttached, Resource = "@xml/device_filter")] 52 | ``` 53 | 54 | **6.** Refer to [MainActivity.cs](https://github.com/anotherlab/UsbSerialForAndroid/blob/master/UsbSerialExampleApp/MainActivity.cs) in the example app to see how connect to a serial device and read data from it. 55 | 56 | ## Working with unrecognized devices 57 | The UsbSerialForAndroid has been compiled with the Vendor ID/Product ID pairs for many common serial devices. If you have a device that is not defined by the library, but will work with one of the drivers, you can manually add the VID/PID pair. If you have a device that is not in the GetSupportedDevices() method for that driver, you can submit a pull request that adds the vendor and product IDs to that driver. 58 | 59 | UsbSerialProber is a class to help you find and instantiate compatible 60 | UsbSerialDrivers from the tree of connected UsbDevices. Normally, you will use 61 | the default prober returned by ``UsbSerialProber.getDefaultProber()``, which 62 | uses the built-in list of well-known VIDs and PIDs that are supported by our 63 | drivers. 64 | 65 | To use your own set of rules, create and use a custom prober: 66 | 67 | ```C# 68 | // Probe for our custom CDC devices, which use VID 0x1234 69 | // and PIDS 0x0001 and 0x0002. 70 | var table = UsbSerialProber.DefaultProbeTable; 71 | table.AddProduct(0x1b4f, 0x0008, typeof(CdcAcmSerialDriver)); // IOIO OTG 72 | 73 | table.AddProduct(0x09D8, 0x0420, typeof(CdcAcmSerialDriver)); // Elatec TWN4 74 | 75 | var prober = new UsbSerialProber(table); 76 | List drivers = prober.FindAllDrivers(usbManager); 77 | // ... 78 | ``` 79 | 80 | Of course, nothing requires you to use UsbSerialProber at all: you can instantiate driver classes directly if you know what you're doing; just supply a compatible UsbDevice. 81 | 82 | 83 | ## Compatible Devices 84 | 85 | * *Serial chips:* FT232R, CDC/ACM (eg Arduino Uno) and possibly others. 86 | See [CompatibleSerialDevices](https://github.com/mik3y/usb-serial-for-android/wiki/Compatible-Serial-Devices). 87 | * *Android phones and tablets:* Nexus 7, Motorola Xoom, and many others. 88 | See [CompatibleAndroidDevices](https://github.com/mik3y/usb-serial-for-android/wiki/Compatible-Android-Devices). 89 | 90 | ## Additional information 91 | 92 | This is a port of the usb-serial-for-android library and code examples written for it can be adapted to C# without much effort. 93 | 94 | For common problems, see the 95 | [Troubleshooting](https://github.com/mik3y/usb-serial-for-android/wiki/Troubleshooting) 96 | wiki page for usb-serial-for-android library. For other help and discussion, please join the usb-serial-for-android Google Group, 97 | [usb-serial-for-android](https://groups.google.com/forum/?fromgroups#!forum/usb-serial-for-android). These two resources are for the Android Java version, but this library is port of that code base. 98 | 99 | Pull Requests are welcome, but please include what hardware was used for testing. We do not have the hardware or the bandwidth to test the various chipsets supported by the library. 100 | 101 | We will do our best to repond to reported issues. If you have a code fix or suggestion, we are only looking at changes submitted as pull requests. 102 | 103 | For more information about contributing or reporting an issue, please see [](https://github.com/anotherlab/UsbSerialForAndroid/blob/main/CONTRIBUTING.md) for more information for what we are looking for and how to get started. 104 | 105 | ## Author, License, and Copyright 106 | 107 | This library is licensed under the MIT License. Please see [LICENSE.txt](https://github.com/anotherlab/UsbSerialForAndroid/blob/main/LICENSE.txt) for the complete license. 108 | 109 | Copyright 2017, Tyler Technologies. All Rights Reserved. Portions of this library are based on the [usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) and [XamarinUsbSerial](https://bitbucket.org/lusovu/xamarinusbserial) libraries. Their rights remain intact. 110 | -------------------------------------------------------------------------------- /UsbSerialExampleApp/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /UsbSerialExampleApp/Assets/AboutAssets.txt: -------------------------------------------------------------------------------- 1 | Any raw assets you want to be deployed with your application can be placed in 2 | this directory (and child directories) and given a Build Action of "AndroidAsset". 3 | 4 | These files will be deployed with you package and will be accessible using Android's 5 | AssetManager, like this: 6 | 7 | public class ReadAsset : Activity 8 | { 9 | protected override void OnCreate (Bundle bundle) 10 | { 11 | base.OnCreate (bundle); 12 | 13 | InputStream input = Assets.Open ("my_asset.txt"); 14 | } 15 | } 16 | 17 | Additionally, some Android functions will automatically load asset files: 18 | 19 | Typeface tf = Typeface.CreateFromAsset (Context.Assets, "fonts/samplefont.ttf"); -------------------------------------------------------------------------------- /UsbSerialExampleApp/GettingStarted.Xamarin: -------------------------------------------------------------------------------- 1 | 2 | GS\Android\CS\AndroidApp\GettingStarted.html 3 | false 4 | -------------------------------------------------------------------------------- /UsbSerialExampleApp/MainActivity.cs: -------------------------------------------------------------------------------- 1 | /* Copyright 2017 Tyler Technologies Inc. 2 | * 3 | * Project home page: https://github.com/anotherlab/xamarin-usb-serial-for-android 4 | * Portions of this library are based on usb-serial-for-android (https://github.com/mik3y/usb-serial-for-android). 5 | * Portions of this library are based on Xamarin USB Serial for Android (https://bitbucket.org/lusovu/xamarinusbserial). 6 | */ 7 | 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Threading.Tasks; 11 | using Android.App; 12 | using Android.Content; 13 | using Android.Hardware.Usb; 14 | using Android.Runtime; 15 | using Android.Views; 16 | using Android.Widget; 17 | using Android.OS; 18 | using Android.Util; 19 | using Hoho.Android.UsbSerial.Driver; 20 | using Hoho.Android.UsbSerial.Extensions; 21 | using Hoho.Android.UsbSerial.Util; 22 | 23 | 24 | [assembly: UsesFeature("android.hardware.usb.host")] 25 | 26 | 27 | namespace UsbSerialExampleApp 28 | { 29 | [Activity(Label = "UsbSerialExampleApp", MainLauncher = true, Icon = "@drawable/icon")] 30 | [IntentFilter(new[] { UsbManager.ActionUsbDeviceAttached })] 31 | [MetaData(UsbManager.ActionUsbDeviceAttached, Resource = "@xml/device_filter")] 32 | public class MainActivity : Activity 33 | { 34 | static readonly string TAG = typeof(MainActivity).Name; 35 | const string ACTION_USB_PERMISSION = "com.hoho.android.usbserial.examples.USB_PERMISSION"; 36 | 37 | UsbManager usbManager; 38 | ListView listView; 39 | TextView progressBarTitle; 40 | ProgressBar progressBar; 41 | 42 | UsbSerialPortAdapter adapter; 43 | BroadcastReceiver detachedReceiver; 44 | UsbSerialPort selectedPort; 45 | 46 | 47 | protected override void OnCreate(Bundle bundle) 48 | { 49 | base.OnCreate(bundle); 50 | 51 | // Set our view from the "main" layout resource 52 | SetContentView(Resource.Layout.Main); 53 | 54 | usbManager = GetSystemService(Context.UsbService) as UsbManager; 55 | listView = FindViewById(Resource.Id.deviceList); 56 | progressBar = FindViewById(Resource.Id.progressBar); 57 | progressBarTitle = FindViewById(Resource.Id.progressBarTitle); 58 | } 59 | 60 | protected override async void OnResume() 61 | { 62 | base.OnResume(); 63 | 64 | adapter = new UsbSerialPortAdapter(this); 65 | listView.Adapter = adapter; 66 | 67 | listView.ItemClick += async (sender, e) => { 68 | await OnItemClick(sender, e); 69 | }; 70 | 71 | await PopulateListAsync(); 72 | 73 | //register the broadcast receivers 74 | detachedReceiver = new UsbDeviceDetachedReceiver(this); 75 | RegisterReceiver(detachedReceiver, new IntentFilter(UsbManager.ActionUsbDeviceDetached)); 76 | } 77 | protected override void OnPause() 78 | { 79 | base.OnPause(); 80 | 81 | // unregister the broadcast receivers 82 | var temp = detachedReceiver; // copy reference for thread safety 83 | if (temp != null) 84 | UnregisterReceiver(temp); 85 | } 86 | internal static Task> FindAllDriversAsync(UsbManager usbManager) 87 | { 88 | // using the default probe table 89 | // return UsbSerialProber.DefaultProber.FindAllDriversAsync (usbManager); 90 | 91 | // adding a custom driver to the default probe table 92 | var table = UsbSerialProber.DefaultProbeTable; 93 | table.AddProduct(0x1b4f, 0x0008, typeof(CdcAcmSerialDriver)); // IOIO OTG 94 | 95 | table.AddProduct(0x09D8, 0x0420, typeof(CdcAcmSerialDriver)); // Elatec TWN4 96 | 97 | var prober = new UsbSerialProber(table); 98 | return prober.FindAllDriversAsync(usbManager); 99 | } 100 | 101 | async Task OnItemClick(object sender, AdapterView.ItemClickEventArgs e) 102 | { 103 | Log.Info(TAG, "Pressed item " + e.Position); 104 | if (e.Position >= adapter.Count) 105 | { 106 | Log.Info(TAG, "Illegal position."); 107 | return; 108 | } 109 | 110 | // request user permission to connect to device 111 | // NOTE: no request is shown to user if permission already granted 112 | selectedPort = adapter.GetItem(e.Position); 113 | var permissionGranted = await usbManager.RequestPermissionAsync(selectedPort.Driver.Device, this); 114 | if (permissionGranted) 115 | { 116 | // start the SerialConsoleActivity for this device 117 | var newIntent = new Intent(this, typeof(SerialConsoleActivity)); 118 | newIntent.PutExtra(SerialConsoleActivity.EXTRA_TAG, new UsbSerialPortInfo(selectedPort)); 119 | StartActivity(newIntent); 120 | } 121 | } 122 | 123 | async Task PopulateListAsync() 124 | { 125 | ShowProgressBar(); 126 | 127 | Log.Info(TAG, "Refreshing device list ..."); 128 | 129 | var drivers = await FindAllDriversAsync(usbManager); 130 | 131 | adapter.Clear(); 132 | foreach (var driver in drivers) 133 | { 134 | var ports = driver.Ports; 135 | Log.Info(TAG, string.Format("+ {0}: {1} port{2}", driver, ports.Count, ports.Count == 1 ? string.Empty : "s")); 136 | foreach (var port in ports) 137 | adapter.Add(port); 138 | } 139 | 140 | adapter.NotifyDataSetChanged(); 141 | progressBarTitle.Text = string.Format("{0} device{1} found", adapter.Count, adapter.Count == 1 ? string.Empty : "s"); 142 | HideProgressBar(); 143 | Log.Info(TAG, "Done refreshing, " + adapter.Count + " entries found."); 144 | } 145 | 146 | void ShowProgressBar() 147 | { 148 | progressBar.Visibility = ViewStates.Visible; 149 | progressBarTitle.Text = GetString(Resource.String.refreshing); 150 | } 151 | 152 | void HideProgressBar() 153 | { 154 | progressBar.Visibility = ViewStates.Invisible; 155 | } 156 | 157 | 158 | #region UsbSerialPortAdapter implementation 159 | 160 | class UsbSerialPortAdapter : ArrayAdapter 161 | { 162 | public UsbSerialPortAdapter(Context context) 163 | : base(context, global::Android.Resource.Layout.SimpleExpandableListItem2) 164 | { 165 | } 166 | 167 | public override View GetView(int position, View convertView, ViewGroup parent) 168 | { 169 | var row = convertView; 170 | if (row == null) 171 | { 172 | var inflater = Context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater; 173 | row = inflater.Inflate(global::Android.Resource.Layout.SimpleListItem2, null); 174 | } 175 | 176 | var port = this.GetItem(position); 177 | var driver = port.GetDriver(); 178 | var device = driver.GetDevice(); 179 | 180 | var title = string.Format("Vendor {0} Product {1}", 181 | HexDump.ToHexString((short)device.VendorId), 182 | HexDump.ToHexString((short)device.ProductId)); 183 | row.FindViewById(global::Android.Resource.Id.Text1).Text = title; 184 | 185 | var subtitle = device.Class.SimpleName; 186 | row.FindViewById(global::Android.Resource.Id.Text2).Text = subtitle; 187 | 188 | return row; 189 | } 190 | } 191 | 192 | #endregion 193 | 194 | #region UsbDeviceDetachedReceiver implementation 195 | 196 | class UsbDeviceDetachedReceiver 197 | : BroadcastReceiver 198 | { 199 | readonly string TAG = typeof(UsbDeviceDetachedReceiver).Name; 200 | readonly MainActivity activity; 201 | 202 | public UsbDeviceDetachedReceiver(MainActivity activity) 203 | { 204 | this.activity = activity; 205 | } 206 | 207 | public async override void OnReceive(Context context, Intent intent) 208 | { 209 | var device = intent.GetParcelableExtra(UsbManager.ExtraDevice) as UsbDevice; 210 | 211 | Log.Info(TAG, "USB device detached: " + device.DeviceName); 212 | 213 | await activity.PopulateListAsync(); 214 | } 215 | } 216 | 217 | #endregion 218 | 219 | 220 | } 221 | } 222 | 223 | -------------------------------------------------------------------------------- /UsbSerialExampleApp/Resources/AboutResources.txt: -------------------------------------------------------------------------------- 1 | Images, layout descriptions, binary blobs and string dictionaries can be included 2 | in your application as resource files. Various Android APIs are designed to 3 | operate on the resource IDs instead of dealing with images, strings or binary blobs 4 | directly. 5 | 6 | For example, a sample Android app that contains a user interface layout (main.axml), 7 | an internationalization string table (strings.xml) and some icons (drawable-XXX/icon.png) 8 | would keep its resources in the "Resources" directory of the application: 9 | 10 | Resources/ 11 | drawable/ 12 | icon.png 13 | 14 | layout/ 15 | main.axml 16 | 17 | values/ 18 | strings.xml 19 | 20 | In order to get the build system to recognize Android resources, set the build action to 21 | "AndroidResource". The native Android APIs do not operate directly with filenames, but 22 | instead operate on resource IDs. When you compile an Android application that uses resources, 23 | the build system will package the resources for distribution and generate a class called "R" 24 | (this is an Android convention) that contains the tokens for each one of the resources 25 | included. For example, for the above Resources layout, this is what the R class would expose: 26 | 27 | public class R { 28 | public class drawable { 29 | public const int icon = 0x123; 30 | } 31 | 32 | public class layout { 33 | public const int main = 0x456; 34 | } 35 | 36 | public class strings { 37 | public const int first_string = 0xabc; 38 | public const int second_string = 0xbcd; 39 | } 40 | } 41 | 42 | You would then use R.drawable.icon to reference the drawable/icon.png file, or R.layout.main 43 | to reference the layout/main.axml file, or R.strings.first_string to reference the first 44 | string in the dictionary file values/strings.xml. -------------------------------------------------------------------------------- /UsbSerialExampleApp/Resources/drawable/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anotherlab/UsbSerialForAndroid/9cc3ee838ec531861bb4d8f03fe3b822df269801/UsbSerialExampleApp/Resources/drawable/Icon.png -------------------------------------------------------------------------------- /UsbSerialExampleApp/Resources/layout/Main.axml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 14 | 23 | 30 | 35 | -------------------------------------------------------------------------------- /UsbSerialExampleApp/Resources/layout/serial_console.axml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 13 |