├── examples
└── SerialTerminal
│ ├── Pages
│ ├── Index.razor
│ └── PortScan.razor
│ ├── wwwroot
│ ├── favicon.ico
│ ├── css
│ │ ├── open-iconic
│ │ │ ├── font
│ │ │ │ ├── fonts
│ │ │ │ │ ├── open-iconic.eot
│ │ │ │ │ ├── open-iconic.otf
│ │ │ │ │ ├── open-iconic.ttf
│ │ │ │ │ └── open-iconic.woff
│ │ │ │ └── css
│ │ │ │ │ └── open-iconic-bootstrap.min.css
│ │ │ ├── ICON-LICENSE
│ │ │ ├── README.md
│ │ │ └── FONT-LICENSE
│ │ └── app.css
│ └── index.html
│ ├── Resources
│ ├── Fonts
│ │ └── OpenSans-Regular.ttf
│ ├── AppIcon
│ │ ├── appicon.svg
│ │ └── appiconfg.svg
│ ├── Raw
│ │ └── AboutAssets.txt
│ ├── Splash
│ │ └── splash.svg
│ └── Images
│ │ └── dotnet_bot.svg
│ ├── Properties
│ └── launchSettings.json
│ ├── MainPage.xaml.cs
│ ├── App.xaml.cs
│ ├── Platforms
│ ├── Android
│ │ ├── Resources
│ │ │ └── values
│ │ │ │ └── colors.xml
│ │ ├── AndroidManifest.xml
│ │ ├── MainApplication.cs
│ │ └── MainActivity.cs
│ ├── iOS
│ │ ├── AppDelegate.cs
│ │ ├── Program.cs
│ │ └── Info.plist
│ ├── MacCatalyst
│ │ ├── AppDelegate.cs
│ │ ├── Program.cs
│ │ └── Info.plist
│ ├── Windows
│ │ ├── App.xaml
│ │ ├── app.manifest
│ │ ├── App.xaml.cs
│ │ └── Package.appxmanifest
│ └── Tizen
│ │ ├── Main.cs
│ │ └── tizen-manifest.xml
│ ├── _Imports.razor
│ ├── Shared
│ ├── MainLayout.razor
│ ├── NavMenu.razor
│ ├── NavMenu.razor.css
│ └── MainLayout.razor.css
│ ├── Main.razor
│ ├── MauiProgram.cs
│ ├── MainPage.xaml
│ ├── App.xaml
│ └── SerialTerminal.csproj
├── .dockerignore
├── README.md
├── src
└── Maui.Serial
│ ├── Platforms
│ ├── Android
│ │ ├── Usb
│ │ │ ├── UsbDeviceDriverId.cs
│ │ │ ├── UsbDeviceDriverSupport.cs
│ │ │ ├── ParcelableCreator.cs
│ │ │ ├── UsbDeviceDriverAttribute.cs
│ │ │ ├── UsbSerialDriver.cs
│ │ │ ├── UsbDeviceDriver.cs
│ │ │ ├── UsbManagerExtensions.cs
│ │ │ ├── UsbSerialRuntimeException.cs
│ │ │ ├── UsbPermissionReceiver.cs
│ │ │ ├── UsbDeviceInfo.cs
│ │ │ ├── UsbSupport.cs
│ │ │ ├── UsbConnectionDriver.cs
│ │ │ ├── UsbSerialPort.cs
│ │ │ ├── UsbId.cs
│ │ │ └── UsbDeviceProber.cs
│ │ ├── EventHandlerExtensions.cs
│ │ ├── Drivers
│ │ │ ├── CommonUsbSerialDriver.cs
│ │ │ ├── Ch43x
│ │ │ │ ├── Ch340UsbSerialDriver.cs
│ │ │ │ └── Ch340UsbSerialPort.cs
│ │ │ ├── Ftdi
│ │ │ │ ├── FtdiUsbSerialDriver.cs
│ │ │ │ └── FtdiUsbSerialPort.cs
│ │ │ ├── STM32
│ │ │ │ ├── STM32UsbSerialDriver.cs
│ │ │ │ └── STM32UsbSerialPort.cs
│ │ │ ├── Cp21xx
│ │ │ │ ├── Cp21xxUsbSerialDriver.cs
│ │ │ │ └── Cp21xxUsbSerialPortDriver.cs
│ │ │ ├── Prolific
│ │ │ │ ├── ProlificUsbSerialDriver.cs
│ │ │ │ └── ProlificUsbSerialPortDriver.cs
│ │ │ ├── CdcAcm
│ │ │ │ ├── CdcAcmUsbSerialDriver.cs
│ │ │ │ └── CdcAcmUsbSerialPort.cs
│ │ │ └── CommonUsbSerialPort.cs
│ │ ├── BufferExtensions.cs
│ │ ├── SerialPortPlatform.cs
│ │ ├── PollingTask.cs
│ │ └── SerialPortAndroid.cs
│ ├── Tizen
│ │ └── SerialPortPlatform.cs
│ ├── iOS
│ │ └── SerialPortPlatform.cs
│ ├── MacCatalyst
│ │ └── SerialPortPlatform.cs
│ └── Windows
│ │ ├── SerialPortPlatform.cs
│ │ └── SerialPortWindows.cs
│ ├── DataBits.cs
│ ├── StopBits.cs
│ ├── Parity.cs
│ ├── FlowControl.cs
│ ├── SerialPortPlatform.cs
│ ├── SerialPortManager.cs
│ ├── SerialPortDataReceivedEventArgs.cs
│ ├── SerialPortErrorEventArgs.cs
│ ├── ISerialPort.cs
│ ├── SerialPortParameters.cs
│ ├── Maui.Serial.csproj
│ └── SerialPortBase.cs
├── .gitattributes
├── LICENSE
├── Maui.Serial.sln
├── .editorconfig
└── .gitignore
/examples/SerialTerminal/Pages/Index.razor:
--------------------------------------------------------------------------------
1 | @page "/"
2 |
3 |
Serial Terminal
4 |
5 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .dockerignore
2 | .env
3 | .git
4 | .gitignore
5 | .vs
6 | .vscode
7 | */bin
8 | */obj
9 | **/.toolstarget
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pvagnozzi/Maui.SerialPort/HEAD/examples/SerialTerminal/wwwroot/favicon.ico
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Maui.SerialPort
2 |
3 | Maui Library for handling serial port in Windows & Android.
4 |
5 | Based on https://github.com/anotherlab/UsbSerialForAndroid
6 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Resources/Fonts/OpenSans-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pvagnozzi/Maui.SerialPort/HEAD/examples/SerialTerminal/Resources/Fonts/OpenSans-Regular.ttf
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbDeviceDriverId.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial.Platforms.Android.Usb;
2 |
3 | public record UsbDeviceDriverId(int VendorId, int DeviceId);
4 |
5 |
--------------------------------------------------------------------------------
/src/Maui.Serial/DataBits.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public enum DataBits
4 | {
5 | Bits5 = 5,
6 | Bits6 = 6,
7 | Bits7 = 7,
8 | Bits8 = 8,
9 | }
10 |
11 |
--------------------------------------------------------------------------------
/src/Maui.Serial/StopBits.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public enum StopBits
4 | {
5 | NotSet = -1,
6 | One = 1,
7 | OnePointFive = 3,
8 | Two = 2
9 | }
10 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Parity.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public enum Parity
4 | {
5 | None = 0,
6 | Odd = 1,
7 | Even = 2,
8 | Mark = 3,
9 | Space = 4
10 | }
11 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbDeviceDriverSupport.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial.Platforms.Android.Usb;
2 |
3 | public record UsbDeviceDriverSupport(int VendorId, int[] DeviceIds);
4 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "Windows Machine": {
4 | "commandName": "MsixPackage",
5 | "nativeDebugging": false
6 | }
7 | }
8 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pvagnozzi/Maui.SerialPort/HEAD/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.eot
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.otf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pvagnozzi/Maui.SerialPort/HEAD/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.otf
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pvagnozzi/Maui.SerialPort/HEAD/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pvagnozzi/Maui.SerialPort/HEAD/examples/SerialTerminal/wwwroot/css/open-iconic/font/fonts/open-iconic.woff
--------------------------------------------------------------------------------
/src/Maui.Serial/FlowControl.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | [Flags]
4 | public enum FlowControl
5 | {
6 | None = 0,
7 | RtsCtsIn = 1,
8 | RtsCtsOut = 2,
9 | XOnXOffIn = 4,
10 | XOnXOffOut = 8
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/MainPage.xaml.cs:
--------------------------------------------------------------------------------
1 | namespace SerialTerminal
2 | {
3 | public partial class MainPage : ContentPage
4 | {
5 | public MainPage()
6 | {
7 | InitializeComponent();
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/SerialPortPlatform.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | internal static partial class SerialPortPlatform
4 | {
5 | internal static partial IList GetPortNames();
6 |
7 | internal static partial ISerialPort GetPort(string portName);
8 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/App.xaml.cs:
--------------------------------------------------------------------------------
1 | namespace SerialTerminal
2 | {
3 | public partial class App : Application
4 | {
5 | public App()
6 | {
7 | InitializeComponent();
8 |
9 | MainPage = new MainPage();
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Resources/AppIcon/appicon.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Android/Resources/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #512BD4
4 | #2B0B98
5 | #2B0B98
6 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/iOS/AppDelegate.cs:
--------------------------------------------------------------------------------
1 | using Foundation;
2 |
3 | namespace SerialTerminal
4 | {
5 | [Register("AppDelegate")]
6 | public class AppDelegate : MauiUIApplicationDelegate
7 | {
8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
9 | }
10 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/SerialPortManager.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public static class SerialPortManager
4 | {
5 | public static IList GetPortNames() => SerialPortPlatform.GetPortNames();
6 |
7 | public static ISerialPort GetPort(string portName) => SerialPortPlatform.GetPort(portName);
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/MacCatalyst/AppDelegate.cs:
--------------------------------------------------------------------------------
1 | using Foundation;
2 |
3 | namespace SerialTerminal
4 | {
5 | [Register("AppDelegate")]
6 | public class AppDelegate : MauiUIApplicationDelegate
7 | {
8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
9 | }
10 | }
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto eol=lf
3 |
4 | *.cs text diff=csharp
5 | *.cshtml text diff=html
6 | *.csx text diff=csharp
7 | *.sln text merge=union
8 | *.csproj text merge=union
9 | *.sh text diff=bash
10 | *.env text
11 | *ockerfile text
--------------------------------------------------------------------------------
/examples/SerialTerminal/_Imports.razor:
--------------------------------------------------------------------------------
1 | @using System.Net.Http
2 | @using Microsoft.AspNetCore.Components.Forms
3 | @using Microsoft.AspNetCore.Components.Routing
4 | @using Microsoft.AspNetCore.Components.Web
5 | @using Microsoft.AspNetCore.Components.Web.Virtualization
6 | @using Microsoft.JSInterop
7 | @using SerialTerminal
8 | @using SerialTerminal.Shared
9 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Windows/App.xaml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Tizen/SerialPortPlatform.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Maui.Serial;
3 |
4 | internal static partial class SerialPortPlatform
5 | {
6 | internal static partial IList GetPortNames() => throw new NotSupportedException();
7 |
8 | internal static partial ISerialPort GetPort(string portName) => throw new NotSupportedException();
9 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/iOS/SerialPortPlatform.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Maui.Serial;
3 |
4 | internal static partial class SerialPortPlatform
5 | {
6 | internal static partial IList GetPortNames() => throw new NotSupportedException();
7 |
8 | internal static partial ISerialPort GetPort(string portName) => throw new NotSupportedException();
9 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/MacCatalyst/SerialPortPlatform.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable once CheckNamespace
2 | namespace Maui.Serial;
3 |
4 | internal static partial class SerialPortPlatform
5 | {
6 | internal static partial IList GetPortNames() => throw new NotSupportedException();
7 |
8 | internal static partial ISerialPort GetPort(string portName) => throw new NotSupportedException();
9 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/ParcelableCreator.cs:
--------------------------------------------------------------------------------
1 | using Android.OS;
2 | using Object = Java.Lang.Object;
3 |
4 | namespace Maui.Serial.Platforms.Android.Usb;
5 |
6 | public sealed class ParcelableCreator : Object, IParcelableCreator
7 | {
8 | public Object CreateFromParcel(Parcel parcel) => new UsbDeviceInfo(parcel);
9 |
10 | public Object[] NewArray(int size) => new Object[size];
11 | }
12 |
--------------------------------------------------------------------------------
/src/Maui.Serial/SerialPortDataReceivedEventArgs.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public enum SerialDataEventType
4 | {
5 | Chars,
6 | Eof
7 | }
8 |
9 | public class SerialPortDataReceivedEventArgs : EventArgs
10 | {
11 | public SerialPortDataReceivedEventArgs(SerialDataEventType eventType = SerialDataEventType.Chars)
12 | {
13 | EventType = eventType;
14 | }
15 |
16 | public SerialDataEventType EventType { get; }
17 | }
18 |
--------------------------------------------------------------------------------
/src/Maui.Serial/SerialPortErrorEventArgs.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public enum SerialPortError
4 | {
5 | Overrun = 2,
6 | RxParity = 4,
7 | Frame = 8,
8 | TxFull = 256,
9 | }
10 |
11 | public class SerialPortErrorEventArgs : EventArgs
12 | {
13 | public SerialPortErrorEventArgs(SerialPortError eventType)
14 | {
15 | EventType = eventType;
16 | }
17 |
18 | public SerialPortError EventType { get; }
19 | }
20 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Windows/SerialPortPlatform.cs:
--------------------------------------------------------------------------------
1 | using System.IO.Ports;
2 | using Maui.Serial.Platforms.Windows;
3 |
4 | // ReSharper disable once CheckNamespace
5 | namespace Maui.Serial;
6 |
7 | internal static partial class SerialPortPlatform
8 | {
9 | internal static partial IList GetPortNames() => SerialPort.GetPortNames();
10 |
11 | internal static partial ISerialPort GetPort(string portName) => new SerialPortWindows(portName);
12 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Shared/MainLayout.razor:
--------------------------------------------------------------------------------
1 | @inherits LayoutComponentBase
2 |
3 |
4 |
7 |
8 |
9 |
12 |
13 |
14 | @Body
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Tizen/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.Maui;
3 | using Microsoft.Maui.Hosting;
4 |
5 | namespace SerialTerminal
6 | {
7 | internal class Program : MauiApplication
8 | {
9 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
10 |
11 | static void Main(string[] args)
12 | {
13 | var app = new Program();
14 | app.Run(args);
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Android/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Android/MainApplication.cs:
--------------------------------------------------------------------------------
1 | using Android.App;
2 | using Android.Runtime;
3 |
4 | namespace SerialTerminal
5 | {
6 | [Application]
7 | public class MainApplication : MauiApplication
8 | {
9 | public MainApplication(IntPtr handle, JniHandleOwnership ownership)
10 | : base(handle, ownership)
11 | {
12 | }
13 |
14 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
15 | }
16 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Main.razor:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Sorry, there's nothing at this address.
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Android/MainActivity.cs:
--------------------------------------------------------------------------------
1 | using Android.App;
2 | using Android.Content.PM;
3 | using Android.OS;
4 |
5 | namespace SerialTerminal
6 | {
7 | [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
8 | public class MainActivity : MauiAppCompatActivity
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/iOS/Program.cs:
--------------------------------------------------------------------------------
1 | using ObjCRuntime;
2 | using UIKit;
3 |
4 | namespace SerialTerminal
5 | {
6 | public class Program
7 | {
8 | // This is the main entry point of the application.
9 | static void Main(string[] args)
10 | {
11 | // if you want to use a different Application Delegate class from "AppDelegate"
12 | // you can specify it here.
13 | UIApplication.Main(args, null, typeof(AppDelegate));
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/MacCatalyst/Program.cs:
--------------------------------------------------------------------------------
1 | using ObjCRuntime;
2 | using UIKit;
3 |
4 | namespace SerialTerminal
5 | {
6 | public class Program
7 | {
8 | // This is the main entry point of the application.
9 | static void Main(string[] args)
10 | {
11 | // if you want to use a different Application Delegate class from "AppDelegate"
12 | // you can specify it here.
13 | UIApplication.Main(args, null, typeof(AppDelegate));
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/EventHandlerExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace Maui.Serial.Platforms.Android;
4 |
5 | public static class EventHandlerExtensions
6 | {
7 | [DebuggerStepThrough]
8 | public static void Raise(this EventHandler handler, object sender, EventArgs e) =>
9 | Volatile.Read(ref handler)?.Invoke(sender, e);
10 |
11 | [DebuggerStepThrough]
12 | public static void Raise(this EventHandler handler, object sender, T e)
13 | where T : EventArgs => Volatile.Read(ref handler)?.Invoke(sender, e);
14 | }
15 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbDeviceDriverAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial.Platforms.Android.Usb;
2 |
3 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
4 | public class UsbDeviceDriverAttribute : Attribute
5 | {
6 | public UsbDeviceDriverAttribute(int vendorId, int[] deviceIds) =>
7 | DriverSupport = new UsbDeviceDriverSupport(vendorId, deviceIds);
8 |
9 | public UsbDeviceDriverSupport DriverSupport { get; }
10 |
11 | public UsbDeviceDriverId[] DriverIds =>
12 | DriverSupport.DeviceIds.Select(x => new UsbDeviceDriverId(DriverSupport.VendorId, x)).ToArray();
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using Android.Hardware.Usb;
2 | using Microsoft.Extensions.Logging;
3 |
4 | namespace Maui.Serial.Platforms.Android.Usb;
5 |
6 | public abstract class UsbSerialDriver : UsbDeviceDriver
7 | {
8 | protected UsbSerialDriver(
9 | UsbManager manager,
10 | UsbDevice device,
11 | ILogger logger) :
12 | base(manager, device, logger)
13 | {
14 | }
15 |
16 | public abstract IEnumerable GetPorts();
17 |
18 | protected abstract UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger);
19 | }
20 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbDeviceDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Microsoft.Extensions.Logging;
4 |
5 | namespace Maui.Serial.Platforms.Android.Usb;
6 |
7 | public abstract class UsbDeviceDriver
8 | {
9 | protected UsbDeviceDriver(
10 | UsbManager manager,
11 | UsbDevice device,
12 | ILogger logger)
13 | {
14 | UsbManager = manager;
15 | UsbDevice = device;
16 | Logger = logger;
17 | }
18 |
19 | public UsbManager UsbManager { get; }
20 | public UsbDevice UsbDevice { get; }
21 | public ILogger Logger { get; }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Maui.Serial/ISerialPort.cs:
--------------------------------------------------------------------------------
1 | namespace Maui.Serial;
2 |
3 | public interface ISerialPort : IDisposable
4 | {
5 | bool IsOpen { get; }
6 | string PortName { get; }
7 | SerialPortParameters Parameters { get; }
8 | void Open(SerialPortParameters parameters = null);
9 | int Read(byte[] data);
10 | string ReadLine();
11 | string ReadExisting();
12 | void Write(byte[] data);
13 | void Write(string value);
14 | void WriteLine(string line);
15 | void Close();
16 |
17 | event EventHandler DataReceived;
18 | event EventHandler ErrorReceived;
19 | }
20 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/MauiProgram.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Logging;
2 |
3 | namespace SerialTerminal;
4 |
5 | public static class MauiProgram
6 | {
7 | public static MauiApp CreateMauiApp()
8 | {
9 | var builder = MauiApp.CreateBuilder();
10 | builder
11 | .UseMauiApp()
12 | .ConfigureFonts(fonts => fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"))
13 | .Services.AddMauiBlazorWebView();
14 |
15 | #if DEBUG
16 | builder.Services.AddBlazorWebViewDeveloperTools();
17 | builder.Logging.AddDebug();
18 | #endif
19 | return builder.Build();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/CommonUsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers;
7 |
8 | public abstract class CommonUsbSerialDriver : UsbSerialDriver
9 | {
10 | protected CommonUsbSerialDriver(
11 | UsbManager manager,
12 | UsbDevice device,
13 | ILogger logger) :
14 | base(manager, device, logger)
15 | {
16 | }
17 |
18 | [DebuggerStepThrough]
19 | public override IEnumerable GetPorts() => new[] { GetPort(UsbManager, UsbDevice, 0, Logger) };
20 | }
21 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbManagerExtensions.cs:
--------------------------------------------------------------------------------
1 | using Android.App;
2 | using Android.Content;
3 | using Android.Hardware.Usb;
4 |
5 | namespace Maui.Serial.Platforms.Android.Usb;
6 |
7 | public static class UsbManagerExtensions
8 | {
9 | public static void RequestPermission(this UsbManager usbManager, UsbDevice usbDevice)
10 | {
11 | if (usbManager.HasPermission(usbDevice))
12 | {
13 | return;
14 | }
15 |
16 | usbManager.RequestPermission(usbDevice, null);
17 | }
18 |
19 | public static UsbManager GetUsbManager(this Activity activity) =>
20 |
21 | (UsbManager)activity.GetSystemService(Context.UsbService);
22 | }
23 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/MainPage.xaml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Resources/Raw/AboutAssets.txt:
--------------------------------------------------------------------------------
1 | Any raw assets you want to be deployed with your application can be placed in
2 | this directory (and child directories). Deployment of the asset to your application
3 | is automatically handled by the following `MauiAsset` Build Action within your `.csproj`.
4 |
5 |
6 |
7 | These files will be deployed with you package and will be accessible using Essentials:
8 |
9 | async Task LoadMauiAsset()
10 | {
11 | using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt");
12 | using var reader = new StreamReader(stream);
13 |
14 | var contents = reader.ReadToEnd();
15 | }
16 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Ch43x/Ch340UsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.Ch43x;
7 |
8 | [UsbDeviceDriver(UsbId.VENDOR_QINHENG, new[] { UsbId.QINHENG_HL340 })]
9 | public class Ch430UsbSerialDriver : CommonUsbSerialDriver
10 | {
11 | public Ch430UsbSerialDriver(UsbManager manager, UsbDevice device, ILogger logger) : base(manager, device, logger)
12 | {
13 | }
14 |
15 | [DebuggerStepThrough]
16 | protected override UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger) =>
17 | new Ch340UsbSerialPortDriver(manager, device, port, logger);
18 | }
19 |
20 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Ftdi/FtdiUsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using Android.Hardware.Usb;
2 | using Maui.Serial.Platforms.Android.Usb;
3 | using Microsoft.Extensions.Logging;
4 |
5 | namespace Maui.Serial.Platforms.Android.Drivers.Ftdi;
6 |
7 | [UsbDeviceDriver(UsbId.VENDOR_FTDI,
8 | new[] { UsbId.FTDI_FT232R, UsbId.FTDI_FT232H, UsbId.FTDI_FT2232H, UsbId.FTDI_FT4232H, UsbId.FTDI_FT231X, })]
9 | public class FtdiUsbSerialDriver : CommonUsbSerialDriver
10 | {
11 | public FtdiUsbSerialDriver(UsbManager manager, UsbDevice device, ILogger logger) :
12 | base(manager, device, logger)
13 | {
14 | }
15 |
16 | protected override UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger) =>
17 | new FtdiUsbSerialPort(manager, device, port, logger);
18 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Windows/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
11 | true/PM
12 | PerMonitorV2, PerMonitor
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Tizen/tizen-manifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | maui-application-title-placeholder
6 | maui-appicon-placeholder
7 |
8 |
9 |
10 |
11 | http://tizen.org/privilege/internet
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbSerialRuntimeException.cs:
--------------------------------------------------------------------------------
1 | using Android.Runtime;
2 | using Java.Lang;
3 |
4 | namespace Maui.Serial.Platforms.Android.Usb;
5 |
6 | public class UsbSerialRuntimeException : RuntimeException
7 | {
8 | public UsbSerialRuntimeException()
9 | {
10 | }
11 |
12 | public UsbSerialRuntimeException(Throwable throwable) :
13 | base(throwable)
14 | {
15 | }
16 |
17 | public UsbSerialRuntimeException(string detailMessage) :
18 | base(detailMessage)
19 | {
20 | }
21 |
22 | public UsbSerialRuntimeException(string detailMessage, Throwable throwable) :
23 | base(detailMessage, throwable)
24 | {
25 | }
26 |
27 | protected UsbSerialRuntimeException(nint javaReference, JniHandleOwnership transfer) :
28 | base(javaReference, transfer)
29 | {
30 | }
31 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/STM32/STM32UsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 | // ReSharper disable InconsistentNaming
6 |
7 | namespace Maui.Serial.Platforms.Android.Drivers.STM32;
8 |
9 | [UsbDeviceDriver(UsbId.VENDOR_STM, new[] { UsbId.STM32_STLINK, UsbId.STM32_VCOM })]
10 | public class STM32UsbSerialDriver : CommonUsbSerialDriver
11 | {
12 | public STM32UsbSerialDriver(UsbManager manager, UsbDevice device, ILogger logger) :
13 | base(manager, device, logger)
14 | {
15 | }
16 |
17 | [DebuggerStepThrough]
18 | protected override UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger) =>
19 | new STM32UsbSerialPortDriver(manager, device, port, logger);
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Cp21xx/Cp21xxUsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.Cp21xx;
7 |
8 | [UsbDeviceDriver(UsbId.VENDOR_SILABS,
9 | new[] { UsbId.SILABS_CP2102, UsbId.SILABS_CP2105, UsbId.SILABS_CP2108, UsbId.SILABS_CP2110 })]
10 | // ReSharper disable once InconsistentNaming
11 | public class Cp21xxUsbSerialDriver : CommonUsbSerialDriver
12 | {
13 | public Cp21xxUsbSerialDriver(UsbManager manager, UsbDevice device, ILogger logger) :
14 | base(manager, device, logger)
15 | {
16 | }
17 |
18 | [DebuggerStepThrough]
19 | protected override UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger) =>
20 | new Cp21xxUsbSerialPort(manager, device, port, logger);
21 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Windows/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.UI.Xaml;
2 |
3 | // To learn more about WinUI, the WinUI project structure,
4 | // and more about our project templates, see: http://aka.ms/winui-project-info.
5 |
6 | namespace SerialTerminal.WinUI
7 | {
8 | ///
9 | /// Provides application-specific behavior to supplement the default Application class.
10 | ///
11 | public partial class App : MauiWinUIApplication
12 | {
13 | ///
14 | /// Initializes the singleton application object. This is the first line of authored code
15 | /// executed, and as such is the logical equivalent of main() or WinMain().
16 | ///
17 | public App()
18 | {
19 | this.InitializeComponent();
20 | }
21 |
22 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
23 | }
24 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | SerialTerminal
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | Loading...
18 |
19 |
20 | An unhandled error has occurred.
21 |
Reload
22 |
🗙
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbPermissionReceiver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Content;
3 | using Android.Hardware.Usb;
4 |
5 | namespace Maui.Serial.Platforms.Android.Usb;
6 |
7 | public class UsbPermissionReceiver : BroadcastReceiver
8 | {
9 | private TaskCompletionSource CompletionSource { get; }
10 |
11 | [DebuggerStepThrough]
12 | public UsbPermissionReceiver(TaskCompletionSource completionSource) =>
13 | CompletionSource = completionSource;
14 |
15 | public override void OnReceive(Context context, Intent intent)
16 | {
17 | #pragma warning disable CA1422
18 | intent.GetParcelableExtra(UsbManager.ExtraDevice);
19 | #pragma warning restore CA1422
20 | var permissionGranted = intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false);
21 | context.UnregisterReceiver(this);
22 | CompletionSource.TrySetResult(permissionGranted);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Pages/PortScan.razor:
--------------------------------------------------------------------------------
1 | @page "/portscan"
2 | @using Maui.Serial
3 |
4 | PortScan
5 |
6 | @if (portNames is null)
7 | {
8 | Loading...
9 | }
10 | else
11 | {
12 |
13 |
14 |
15 | Port Name
16 |
17 |
18 |
19 | @foreach (var portName in portNames)
20 | {
21 |
22 | @portName
23 |
24 | Connect
25 |
26 |
27 | }
28 |
29 |
30 | }
31 |
32 | @code {
33 | private string[] portNames;
34 |
35 | protected override void OnInitialized()
36 | {
37 |
38 | portNames = SerialPortManager.GetPortNames().ToArray();
39 |
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/Maui.Serial/SerialPortParameters.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace Maui.Serial;
4 |
5 | public record SerialPortParameters(int BaudRate = 115200, DataBits DataBits = DataBits.Bits8,
6 | StopBits StopBits = StopBits.One, Parity Partity = Parity.None, FlowControl FlowControl = FlowControl.None,
7 | int ReadBufferSize = 16 * 1024, int WriteBufferSize = 16 * 1024, int ReadTimeout = 2000, int WriteTimeout = 2000,
8 | string NewLine = null, Encoding Encoding = null)
9 | {
10 | public Encoding Encoding { get; } = Encoding ?? Encoding.UTF8;
11 |
12 | public string NewLine { get; } = NewLine ?? "\n";
13 |
14 | public override string ToString() =>
15 | $"BaudRate: {BaudRate}, DataBits: {DataBits}, StopBits: {StopBits}, Partity: {Partity}, FlowControl: {FlowControl}, ReadBufferSize: {ReadBufferSize}, WriteBufferSize: {WriteBufferSize}, ReadTimeout: {ReadTimeout}, WriteTimeout: {WriteTimeout}, NewLine: {NewLine}, Encoding: {Encoding}";
16 | }
17 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Prolific/ProlificUsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.Prolific;
7 |
8 | [UsbDeviceDriver(UsbId.VENDOR_PROLIFIC,
9 | new[]
10 | {
11 | UsbId.PROLIFIC_PL2303, UsbId.PROLIFIC_PL2303GC, UsbId.PROLIFIC_PL2303GB, UsbId.PROLIFIC_PL2303GT,
12 | UsbId.PROLIFIC_PL2303GL, UsbId.PROLIFIC_PL2303GE, UsbId.PROLIFIC_PL2303GS
13 | })]
14 | public class ProlificUsbSerialDriver : CommonUsbSerialDriver
15 | {
16 | public ProlificUsbSerialDriver(UsbManager manager, UsbDevice device, ILogger logger) :
17 | base(manager, device, logger)
18 | {
19 | }
20 |
21 | [DebuggerStepThrough]
22 | protected override UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger) =>
23 | new ProlificUsbSerialPortDriver(manager, device, port, logger);
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Piergiorgio Vagnozzi
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbDeviceInfo.cs:
--------------------------------------------------------------------------------
1 | using Android.OS;
2 | using Java.Interop;
3 |
4 | namespace Maui.Serial.Platforms.Android.Usb;
5 |
6 | public class UsbDeviceInfo : Java.Lang.Object, IParcelable
7 | {
8 | private static readonly IParcelableCreator _creator = new ParcelableCreator();
9 |
10 | [ExportField("CREATOR")]
11 | public static IParcelableCreator GetCreator()
12 | {
13 | return _creator;
14 | }
15 |
16 | public UsbDeviceInfo()
17 | {
18 |
19 | }
20 | public UsbDeviceInfo(UsbDeviceDriver port)
21 | {
22 | var device = port.UsbDevice;
23 | VendorId = device.VendorId;
24 | DeviceId = device.DeviceId;
25 | }
26 |
27 | internal UsbDeviceInfo(Parcel parcel)
28 | {
29 | VendorId = parcel.ReadInt();
30 | DeviceId = parcel.ReadInt();
31 | }
32 |
33 | public int VendorId { get; }
34 | public int DeviceId { get; }
35 | public int DescribeContents() => 0;
36 |
37 | public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
38 | {
39 | dest.WriteInt(VendorId);
40 | dest.WriteInt(DeviceId);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/ICON-LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Waybury
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
--------------------------------------------------------------------------------
/examples/SerialTerminal/App.xaml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 | #512bdf
10 | White
11 |
12 |
16 |
17 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/MacCatalyst/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | UIDeviceFamily
6 |
7 | 1
8 | 2
9 |
10 | UIRequiredDeviceCapabilities
11 |
12 | arm64
13 |
14 | UISupportedInterfaceOrientations
15 |
16 | UIInterfaceOrientationPortrait
17 | UIInterfaceOrientationLandscapeLeft
18 | UIInterfaceOrientationLandscapeRight
19 |
20 | UISupportedInterfaceOrientations~ipad
21 |
22 | UIInterfaceOrientationPortrait
23 | UIInterfaceOrientationPortraitUpsideDown
24 | UIInterfaceOrientationLandscapeLeft
25 | UIInterfaceOrientationLandscapeRight
26 |
27 | XSAppIconAssets
28 | Assets.xcassets/appicon.appiconset
29 |
30 |
31 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Shared/NavMenu.razor:
--------------------------------------------------------------------------------
1 |
9 |
10 |
24 |
25 | @code {
26 | private bool collapseNavMenu = true;
27 |
28 | private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
29 |
30 | private void ToggleNavMenu()
31 | {
32 | collapseNavMenu = !collapseNavMenu;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/iOS/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | LSRequiresIPhoneOS
6 |
7 | UIDeviceFamily
8 |
9 | 1
10 | 2
11 |
12 | UIRequiredDeviceCapabilities
13 |
14 | arm64
15 |
16 | UISupportedInterfaceOrientations
17 |
18 | UIInterfaceOrientationPortrait
19 | UIInterfaceOrientationLandscapeLeft
20 | UIInterfaceOrientationLandscapeRight
21 |
22 | UISupportedInterfaceOrientations~ipad
23 |
24 | UIInterfaceOrientationPortrait
25 | UIInterfaceOrientationPortraitUpsideDown
26 | UIInterfaceOrientationLandscapeLeft
27 | UIInterfaceOrientationLandscapeRight
28 |
29 | XSAppIconAssets
30 | Assets.xcassets/appicon.appiconset
31 |
32 |
33 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Shared/NavMenu.razor.css:
--------------------------------------------------------------------------------
1 | .navbar-toggler {
2 | background-color: rgba(255, 255, 255, 0.1);
3 | }
4 |
5 | .top-row {
6 | height: 3.5rem;
7 | background-color: rgba(0,0,0,0.4);
8 | }
9 |
10 | .navbar-brand {
11 | font-size: 1.1rem;
12 | }
13 |
14 | .oi {
15 | width: 2rem;
16 | font-size: 1.1rem;
17 | vertical-align: text-top;
18 | top: -2px;
19 | }
20 |
21 | .nav-item {
22 | font-size: 0.9rem;
23 | padding-bottom: 0.5rem;
24 | }
25 |
26 | .nav-item:first-of-type {
27 | padding-top: 1rem;
28 | }
29 |
30 | .nav-item:last-of-type {
31 | padding-bottom: 1rem;
32 | }
33 |
34 | .nav-item ::deep a {
35 | color: #d7d7d7;
36 | border-radius: 4px;
37 | height: 3rem;
38 | display: flex;
39 | align-items: center;
40 | line-height: 3rem;
41 | }
42 |
43 | .nav-item ::deep a.active {
44 | background-color: rgba(255,255,255,0.25);
45 | color: white;
46 | }
47 |
48 | .nav-item ::deep a:hover {
49 | background-color: rgba(255,255,255,0.1);
50 | color: white;
51 | }
52 |
53 | @media (min-width: 641px) {
54 | .navbar-toggler {
55 | display: none;
56 | }
57 |
58 | .collapse {
59 | /* Never collapse the sidebar for wide screens */
60 | display: block;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbSupport.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable InconsistentNaming
2 |
3 | namespace Maui.Serial.Platforms.Android.Usb;
4 |
5 | public static class UsbSupport
6 | {
7 | public const int UsbClassAppSpec = 254;
8 | public const int UsbClassAudio = 1;
9 | public const int UsbClassCdcData = 10;
10 | public const int UsbClassComm = 2;
11 | public const int UsbClassContentSec = 13;
12 | public const int UsbClassCscid = 11;
13 | public const int UsbClassHid = 3;
14 | public const int UsbClassHub = 9;
15 | public const int UsbClassMassStorage = 8;
16 | public const int UsbClassMisc = 239;
17 | public const int UsbClassPerInterface = 0;
18 | public const int UsbClassPhysica = 5;
19 | public const int UsbClassPrinter = 7;
20 | public const int UsbClassStillImage = 6;
21 | public const int UsbClassVendorSpec = 255;
22 | public const int UsbClassVideo = 14;
23 | public const int UsbClassWirelessController = 234;
24 | public const int UsbDirOut = 0;
25 | public const int UsbDirIn = 128;
26 | public const int UsbEndpointDirMask = 128;
27 | public const int UsbEndpointNumberMask = 15;
28 | public const int UsbEndpointXferBulk = 2;
29 | public const int UsbEndpointXferControl = 0;
30 | public const int UsbEndpointXferInt = 3;
31 | public const int UsbEndpointXferIsoc = 1;
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/CdcAcm/CdcAcmUsbSerialDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.CdcAcm;
7 |
8 | [UsbDeviceDriver(UsbId.VENDOR_ARDUINO,
9 | new[]
10 | {
11 | UsbId.ARDUINO_UNO, UsbId.ARDUINO_UNO_R3, UsbId.ARDUINO_MEGA_2560, UsbId.ARDUINO_MEGA_2560_R3,
12 | UsbId.ARDUINO_SERIAL_ADAPTER, UsbId.ARDUINO_SERIAL_ADAPTER_R3, UsbId.ARDUINO_MEGA_ADK, UsbId.ARDUINO_LEONARDO,
13 | UsbId.ARDUINO_MICRO,
14 | })]
15 | [UsbDeviceDriver(UsbId.VENDOR_VAN_OOIJEN_TECH, new[] { UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL })]
16 | [UsbDeviceDriver(UsbId.VENDOR_ATMEL, new[] { UsbId.ATMEL_LUFA_CDC_DEMO_APP })]
17 | [UsbDeviceDriver(UsbId.VENDOR_ELATEC,
18 | new[] { UsbId.ELATEC_TWN3_CDC, UsbId.ELATEC_TWN4_MIFARE_NFC, UsbId.ELATEC_TWN4_CDC, })]
19 | [UsbDeviceDriver(UsbId.VENDOR_LEAFLABS, new[] { UsbId.LEAFLABS_MAPLE })]
20 | public class CdcmAcmUsbSerialDriver : CommonUsbSerialDriver
21 | {
22 | public CdcmAcmUsbSerialDriver(UsbManager manager, UsbDevice device, ILogger logger) :
23 | base(manager, device, logger)
24 | {
25 | }
26 |
27 | [DebuggerStepThrough]
28 | protected override UsbSerialPort GetPort(UsbManager manager, UsbDevice device, int port, ILogger logger) =>
29 | new CdcAcmUsbSerialPort(manager, device, port, logger);
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/BufferExtensions.cs:
--------------------------------------------------------------------------------
1 | using Android.Runtime;
2 | using Java.Nio;
3 |
4 | namespace Maui.Serial.Platforms.Android;
5 |
6 | public static class BufferExtensions
7 | {
8 | private static nint _byteBufferClassRef;
9 |
10 | private static nint _byteBufferGetBii;
11 |
12 | public static ByteBuffer GetBuffer(this ByteBuffer buffer, JavaArray dst, int dstOffset, int byteCount)
13 | {
14 | if (_byteBufferClassRef == 0)
15 | {
16 | _byteBufferClassRef = JNIEnv.FindClass("java/nio/ByteBuffer");
17 | }
18 |
19 | if (_byteBufferGetBii == 0)
20 | {
21 | _byteBufferGetBii = JNIEnv.GetMethodID(_byteBufferClassRef, "get", "([BII)Ljava/nio/ByteBuffer;");
22 | }
23 |
24 | return Java.Lang.Object.GetObject(
25 | JNIEnv.CallObjectMethod(buffer.Handle, _byteBufferGetBii, new JValue(dst), new JValue(dstOffset),
26 | new JValue(byteCount)), JniHandleOwnership.TransferLocalRef);
27 | }
28 |
29 | public static byte[] ToByteArray(this ByteBuffer buffer)
30 | {
31 | var classHandle = JNIEnv.FindClass("java/nio/ByteBuffer");
32 | var methodId = JNIEnv.GetMethodID(classHandle, "array", "()[B");
33 | var resultHandle = JNIEnv.CallObjectMethod(buffer.Handle, methodId);
34 | var result = JNIEnv.GetArray(resultHandle);
35 | JNIEnv.DeleteLocalRef(resultHandle);
36 | return result;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbConnectionDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Microsoft.Extensions.Logging;
4 |
5 | namespace Maui.Serial.Platforms.Android.Usb;
6 |
7 | public abstract class UsbConnectionDriver
8 | {
9 | protected UsbConnectionDriver(
10 | UsbManager manager,
11 | UsbDevice device,
12 | ILogger logger)
13 | {
14 | UsbManager = manager;
15 | UsbDevice = device;
16 | Logger = logger;
17 | }
18 |
19 | public ILogger Logger { get; }
20 | public UsbManager UsbManager { get; }
21 | public UsbDevice UsbDevice { get; }
22 | public UsbDeviceConnection UsbConnection { get; protected set; }
23 | public virtual bool IsOpen => UsbConnection is not null;
24 |
25 | public virtual void Open()
26 | {
27 | if (IsOpen)
28 | {
29 | return;
30 | }
31 | UsbConnection = OpenConnection();
32 | }
33 |
34 | public virtual void Close()
35 | {
36 | if (!IsOpen)
37 | {
38 | return;
39 | }
40 |
41 | UsbConnection.Close();
42 | UsbConnection.Dispose();
43 | UsbConnection = null;
44 | }
45 |
46 | [DebuggerStepThrough]
47 | public virtual void Dispose()
48 | {
49 | Close();
50 | GC.SuppressFinalize(this);
51 | }
52 |
53 | [DebuggerStepThrough]
54 | protected virtual UsbDeviceConnection OpenConnection() => UsbManager.OpenDevice(UsbDevice);
55 | }
56 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Shared/MainLayout.razor.css:
--------------------------------------------------------------------------------
1 | .page {
2 | position: relative;
3 | display: flex;
4 | flex-direction: column;
5 | }
6 |
7 | main {
8 | flex: 1;
9 | }
10 |
11 | .sidebar {
12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
13 | }
14 |
15 | .top-row {
16 | background-color: #f7f7f7;
17 | border-bottom: 1px solid #d6d5d5;
18 | justify-content: flex-end;
19 | height: 3.5rem;
20 | display: flex;
21 | align-items: center;
22 | }
23 |
24 | .top-row ::deep a, .top-row ::deep .btn-link {
25 | white-space: nowrap;
26 | margin-left: 1.5rem;
27 | text-decoration: none;
28 | }
29 |
30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover {
31 | text-decoration: underline;
32 | }
33 |
34 | .top-row ::deep a:first-child {
35 | overflow: hidden;
36 | text-overflow: ellipsis;
37 | }
38 |
39 | @media (max-width: 640.98px) {
40 | .top-row:not(.auth) {
41 | display: none;
42 | }
43 |
44 | .top-row.auth {
45 | justify-content: space-between;
46 | }
47 |
48 | .top-row ::deep a, .top-row ::deep .btn-link {
49 | margin-left: 0;
50 | }
51 | }
52 |
53 | @media (min-width: 641px) {
54 | .page {
55 | flex-direction: row;
56 | }
57 |
58 | .sidebar {
59 | width: 250px;
60 | height: 100vh;
61 | position: sticky;
62 | top: 0;
63 | }
64 |
65 | .top-row {
66 | position: sticky;
67 | top: 0;
68 | z-index: 1;
69 | }
70 |
71 | .top-row, article {
72 | padding-left: 2rem !important;
73 | padding-right: 1.5rem !important;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Resources/Splash/splash.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Resources/AppIcon/appiconfg.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Maui.Serial.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0-android;net6.0-ios;net6.0-maccatalyst
5 | $(TargetFrameworks);net6.0-windows10.0.19041.0
6 |
7 |
8 | true
9 | true
10 | enable
11 |
12 | 14.2
13 | 14.0
14 | 21.0
15 | 10.0.17763.0
16 | 10.0.17763.0
17 | 6.5
18 | Maui.SerialPort
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbSerialPort.cs:
--------------------------------------------------------------------------------
1 | using Android.Hardware.Usb;
2 | using Microsoft.Extensions.Logging;
3 | // ReSharper disable InconsistentNaming
4 |
5 | namespace Maui.Serial.Platforms.Android.Usb;
6 |
7 | public abstract class UsbSerialPort : UsbConnectionDriver
8 | {
9 | protected const int DATABITS_5 = 5;
10 | protected const int DATABITS_6 = 6;
11 | protected const int DATABITS_7 = 7;
12 | protected const int DATABITS_8 = 8;
13 |
14 | protected const int FLOWCONTROL_NONE = 0;
15 | protected const int FLOWCONTROL_RTSCTS_IN = 1;
16 | protected const int FLOWCONTROL_RTSCTS_OUT = 2;
17 | protected const int FLOWCONTROL_XONXOFF_IN = 4;
18 | protected const int FLOWCONTROL_XONXOFF_OUT = 8;
19 |
20 | protected const int PARITY_NONE = 0;
21 | protected const int PARITY_ODD = 1;
22 | protected const int PARITY_EVEN = 2;
23 | protected const int PARITY_MARK = 3;
24 | protected const int PARITY_SPACE = 4;
25 |
26 | protected const int STOPBITS_1 = 1;
27 | protected const int STOPBITS_1_5 = 3;
28 | protected const int STOPBITS_2 = 2;
29 |
30 | protected UsbSerialPort(
31 | UsbManager manager,
32 | UsbDevice device,
33 | int portNumber,
34 | ILogger logger) :
35 | base(manager, device, logger)
36 | {
37 | PortNumber = portNumber;
38 | Parameters = new SerialPortParameters();
39 | }
40 | public int PortNumber { get; }
41 | public string PortName => $"{UsbDevice.DeviceName}/{PortNumber}";
42 | public SerialPortParameters Parameters { get; set; }
43 |
44 | public abstract int Read(byte[] dest);
45 | public abstract int Write(byte[] src);
46 | public abstract bool GetCD();
47 | public abstract bool GetCTS();
48 | public abstract bool GetDSR();
49 | public abstract bool GetDTR();
50 | public abstract void SetDTR(bool value);
51 | public abstract bool GetRI();
52 | public abstract bool GetRTS();
53 | public abstract void SetRTS(bool value);
54 | }
55 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Platforms/Windows/Package.appxmanifest:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | $placeholder$
15 | User Name
16 | $placeholder$.png
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/SerialPortPlatform.cs:
--------------------------------------------------------------------------------
1 | using Android.App;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android;
4 | using Maui.Serial.Platforms.Android.Usb;
5 | using Microsoft.Extensions.Logging;
6 |
7 | // ReSharper disable once CheckNamespace
8 | namespace Maui.Serial;
9 |
10 | internal static partial class SerialPortPlatform
11 | {
12 | private static UsbManager _usbManager;
13 |
14 | private static UsbSerialPort[] _ports = Array.Empty();
15 |
16 | internal static partial IList GetPortNames() => GetPortNames(Platform.CurrentActivity);
17 |
18 | internal static partial ISerialPort GetPort(string portName) => new SerialPortAndroid(portName);
19 |
20 | internal static string[] GetPortNames(Activity activity, ILogger logger = null)
21 | {
22 | if (activity is null)
23 | {
24 | throw new ArgumentNullException(nameof(activity));
25 | }
26 | _usbManager = activity.GetUsbManager();
27 |
28 | var usbProber = new UsbDeviceProber(logger);
29 | usbProber.RegisterDriver(typeof(ISerialPort).Assembly);
30 |
31 | if (_usbManager.DeviceList is null)
32 | {
33 | return Array.Empty();
34 | }
35 |
36 | var ports = new List();
37 |
38 | foreach (var device in _usbManager.DeviceList.Values)
39 | {
40 | var driver = usbProber.ProbeDevice(_usbManager, device);
41 |
42 | if (driver is not UsbSerialDriver serilPortDriver)
43 | {
44 | continue;
45 | }
46 |
47 | ports.AddRange(serilPortDriver.GetPorts());
48 | }
49 |
50 | _ports = ports.ToArray();
51 | return _ports.Select(x => x.PortName).ToArray();
52 | }
53 |
54 | internal static UsbSerialPort GetUsbPortByName(string portName)
55 | {
56 | var port = _ports.FirstOrDefault(x => x.PortName == portName);
57 | return port ?? throw new ArgumentException($"Port {portName} does not exists");
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbId.cs:
--------------------------------------------------------------------------------
1 | // ReSharper disable InconsistentNaming
2 |
3 | namespace Maui.Serial.Platforms.Android.Usb;
4 |
5 | public static class UsbId
6 | {
7 | public const int VENDOR_FTDI = 0x0403;
8 | public const int FTDI_FT232R = 0x6001;
9 | public const int FTDI_FT2232H = 0x6010;
10 | public const int FTDI_FT4232H = 0x6011;
11 | public const int FTDI_FT232H = 0x6014;
12 | public const int FTDI_FT231X = 0x6015;
13 | public const int VENDOR_ATMEL = 0x03EB;
14 | public const int ATMEL_LUFA_CDC_DEMO_APP = 0x2044;
15 | public const int VENDOR_ARDUINO = 0x2341;
16 | public const int ARDUINO_UNO = 0x0001;
17 | public const int ARDUINO_MEGA_2560 = 0x0010;
18 | public const int ARDUINO_SERIAL_ADAPTER = 0x003b;
19 | public const int ARDUINO_MEGA_ADK = 0x003f;
20 | public const int ARDUINO_MEGA_2560_R3 = 0x0042;
21 | public const int ARDUINO_UNO_R3 = 0x0043;
22 | public const int ARDUINO_SERIAL_ADAPTER_R3 = 0x0044;
23 | public const int ARDUINO_LEONARDO = 0x8036;
24 | public const int ARDUINO_MICRO = 0x8037;
25 | public const int VENDOR_VAN_OOIJEN_TECH = 0x16c0;
26 | public const int VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL = 0x0483;
27 | public const int VENDOR_LEAFLABS = 0x1eaf;
28 | public const int LEAFLABS_MAPLE = 0x0004;
29 | public const int VENDOR_SILABS = 0x10c4;
30 | public const int SILABS_CP2102 = 0xea60;
31 | public const int SILABS_CP2105 = 0xea70;
32 | public const int SILABS_CP2108 = 0xea71;
33 | public const int SILABS_CP2110 = 0xea80;
34 | public const int VENDOR_PROLIFIC = 0x067b;
35 | public const int PROLIFIC_PL2303 = 0x2303;
36 | public const int PROLIFIC_PL2303GC = 0x23a3;
37 | public const int PROLIFIC_PL2303GB = 0x23b3;
38 | public const int PROLIFIC_PL2303GT = 0x23c3;
39 | public const int PROLIFIC_PL2303GL = 0x23d3;
40 | public const int PROLIFIC_PL2303GE = 0x23e3;
41 | public const int PROLIFIC_PL2303GS = 0x23f3;
42 | public const int VENDOR_QINHENG = 0x1a86;
43 | public const int QINHENG_HL340 = 0x7523;
44 | public const int VENDOR_ELATEC = 0x09D8;
45 | public const int ELATEC_TWN3_CDC = 0x0320;
46 | public const int ELATEC_TWN4_MIFARE_NFC = 0x0406;
47 | public const int ELATEC_TWN4_CDC = 0x0420;
48 | public const int VENDOR_STM = 0x0483;
49 | public const int STM32_STLINK = 0x374B;
50 | public const int STM32_VCOM = 0x5740;
51 | }
52 |
53 |
--------------------------------------------------------------------------------
/Maui.Serial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.5.33502.453
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8A0EC7F2-35BF-4A02-A9EF-E824697CB643}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B74C5158-9733-4208-A56B-B9BF48F6932D}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SerialTerminal", "examples\SerialTerminal\SerialTerminal.csproj", "{2C89AA53-B642-4BA4-B045-9D287283ED71}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Maui.Serial", "src\Maui.Serial\Maui.Serial.csproj", "{1BAEEB74-E30E-4966-98B8-DAF4982B8E6A}"
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {2C89AA53-B642-4BA4-B045-9D287283ED71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {2C89AA53-B642-4BA4-B045-9D287283ED71}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {2C89AA53-B642-4BA4-B045-9D287283ED71}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
23 | {2C89AA53-B642-4BA4-B045-9D287283ED71}.Release|Any CPU.ActiveCfg = Release|Any CPU
24 | {2C89AA53-B642-4BA4-B045-9D287283ED71}.Release|Any CPU.Build.0 = Release|Any CPU
25 | {2C89AA53-B642-4BA4-B045-9D287283ED71}.Release|Any CPU.Deploy.0 = Release|Any CPU
26 | {1BAEEB74-E30E-4966-98B8-DAF4982B8E6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {1BAEEB74-E30E-4966-98B8-DAF4982B8E6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {1BAEEB74-E30E-4966-98B8-DAF4982B8E6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {1BAEEB74-E30E-4966-98B8-DAF4982B8E6A}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(NestedProjects) = preSolution
35 | {2C89AA53-B642-4BA4-B045-9D287283ED71} = {B74C5158-9733-4208-A56B-B9BF48F6932D}
36 | {1BAEEB74-E30E-4966-98B8-DAF4982B8E6A} = {8A0EC7F2-35BF-4A02-A9EF-E824697CB643}
37 | EndGlobalSection
38 | GlobalSection(ExtensibilityGlobals) = postSolution
39 | SolutionGuid = {6057F342-13AD-4EE8-B404-EF463E27A5A8}
40 | EndGlobalSection
41 | EndGlobal
42 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/PollingTask.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace Maui.Serial.Platforms.Android;
4 |
5 | internal class PollingTask : IDisposable
6 | {
7 | private readonly CancellationTokenSource _cancellationTokenSource = new();
8 | private readonly Action _pollingAction;
9 | private readonly TimeSpan _pollingInterval;
10 | private CancellationToken _cancellationToken = CancellationToken.None;
11 | private Task _task;
12 |
13 | public PollingTask(Action action, TimeSpan? interval = null)
14 | {
15 | _pollingAction = action;
16 | _pollingInterval = interval ?? TimeSpan.Zero;
17 | }
18 |
19 | public bool IsRunning => _task is not null && !_task.IsCanceled && !_task.IsCompleted && !_task.IsFaulted && _task.IsCompletedSuccessfully;
20 |
21 | public virtual void Start()
22 | {
23 | if (IsRunning)
24 | {
25 | return;
26 | }
27 |
28 | _cancellationToken = _cancellationTokenSource.Token;
29 | _task = Task.Factory.StartNew(Polling, _cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
30 | }
31 |
32 | public virtual void Stop()
33 | {
34 | if (!IsRunning)
35 | {
36 | return;
37 | }
38 |
39 | _cancellationTokenSource.Cancel();
40 | _task.Wait(10);
41 | }
42 |
43 | [DebuggerStepThrough]
44 | public virtual void Dispose()
45 | {
46 | if (IsRunning)
47 | {
48 | Stop();
49 | }
50 |
51 | GC.SuppressFinalize(this);
52 | }
53 |
54 | protected virtual void Polling()
55 | {
56 | try
57 | {
58 | while (true)
59 | {
60 | _cancellationToken.ThrowIfCancellationRequested();
61 | var startTime = DateTime.Now;
62 | _pollingAction(_cancellationToken);
63 | var duration = DateTime.Now - startTime;
64 | var delay = _pollingInterval - duration;
65 |
66 | if (delay < TimeSpan.Zero)
67 | {
68 | continue;
69 | }
70 |
71 | Task.Delay(delay, _cancellationToken).Wait(_cancellationToken);
72 | }
73 | }
74 | catch (OperationCanceledException)
75 | {
76 | }
77 | }
78 | }
79 |
80 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: https://EditorConfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | # Don't use tabs for indentation.
7 | [*]
8 | indent_style = space
9 | # (Please don't specify an indent_size here; that has too many unintended consequences.)
10 |
11 | [*.cs]
12 | # Instance fields are camelCase and start with _
13 | dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion
14 | dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
15 | dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style
16 | dotnet_naming_symbols.instance_fields.applicable_kinds = field
17 | dotnet_naming_style.instance_field_style.capitalization = camel_case
18 | dotnet_naming_style.instance_field_style.required_prefix = _
19 |
20 | # IDE0055: Fix formatting
21 | dotnet_diagnostic.IDE0055.severity = warning
22 |
23 | # Sort using and Import directives with System.* appearing first
24 | dotnet_sort_system_directives_first = true
25 | dotnet_separate_import_directive_groups = false
26 | dotnet_organize_imports = true
27 |
28 | # Avoid "this." and "Me." if not necessary
29 | dotnet_style_qualification_for_field = false:refactoring
30 | dotnet_style_qualification_for_property = false:refactoring
31 | dotnet_style_qualification_for_method = false:refactoring
32 | dotnet_style_qualification_for_event = false:refactoring
33 |
34 | # Prefer "var" everywhere
35 | csharp_style_var_for_built_in_types = true:suggestion
36 | csharp_style_var_when_type_is_apparent = true:suggestion
37 | csharp_style_var_elsewhere = true:suggestion
38 |
39 | # Suggest more modern language features when available
40 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
41 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
42 | csharp_style_inlined_variable_declaration = true:suggestion
43 | csharp_style_throw_expression = true:suggestion
44 | csharp_style_conditional_delegate_call = true:suggestion
45 |
46 | # CA1822: Make member static
47 | dotnet_diagnostic.CA1822.severity = none
48 |
49 | # IDE0058: Remove unnecessary expression value
50 | dotnet_diagnostic.IDE0058.severity = none
51 |
52 | # IDE0059: Unnecessary assignment to a value
53 | dotnet_diagnostic.IDE0059.severity = error
54 |
55 | # IDE0035: Remove unreachable code
56 | dotnet_diagnostic.IDE0035.severity = error
57 |
58 | # IDE0043: Format string contains invalid placeholder
59 | dotnet_diagnostic.IDE0043.severity = error
60 |
61 | # Omnisharp's formatter breaks with unix-style endings
62 | [*.razor]
63 | end_of_line = crlf
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Windows/SerialPortWindows.cs:
--------------------------------------------------------------------------------
1 | using System.IO.Ports;
2 | using Microsoft.Extensions.Logging;
3 |
4 | // ReSharper disable once CheckNamespace
5 | namespace Maui.Serial.Platforms.Windows;
6 |
7 | public class SerialPortWindows : SerialPortBase
8 | {
9 | public SerialPortWindows(string portName, SerialPortParameters parameters = null, ILogger logger = null) : base(portName,
10 | parameters, logger)
11 | {
12 | }
13 |
14 | protected SerialPort Port { get; private set; }
15 |
16 | protected override void OpenPort(string portName, SerialPortParameters parameters)
17 | {
18 | Port = new SerialPort(PortName, parameters!.BaudRate, ConvertParity(parameters.Partity))
19 | {
20 | ReadBufferSize = Parameters.ReadBufferSize,
21 | ReadTimeout = Parameters.ReadTimeout,
22 | StopBits = System.IO.Ports.StopBits.One,
23 | WriteBufferSize = parameters.WriteBufferSize,
24 | WriteTimeout = parameters.WriteTimeout
25 | };
26 |
27 | Port.Open();
28 | Port.Encoding = parameters.Encoding;
29 | Port.Handshake = Handshake.None;
30 | Port.NewLine = parameters.NewLine;
31 | Port.DataReceived += (_, args) =>
32 | OnDataReceived(args.EventType == SerialData.Chars ? SerialDataEventType.Chars : SerialDataEventType.Eof);
33 | Port.ErrorReceived += (_, _) => OnErrorReceived();
34 | }
35 |
36 | protected override int ReadFromPort(byte[] data) => Port.Read(data, 0, data.Length);
37 |
38 | protected override string ReadLineFromPort()
39 | {
40 | try
41 | {
42 | return Port.ReadLine();
43 | }
44 | catch (TimeoutException)
45 | {
46 | return string.Empty;
47 | }
48 | }
49 |
50 | protected override string ReadExistingFromPort() => Port.ReadExisting();
51 |
52 | protected override void WriteToPort(byte[] data) => Port.Write(data, 0, data.Length);
53 |
54 | protected override void WriteToPort(string value) => Port.Write(value);
55 |
56 | protected override void WriteLineToPort(string line) => Port.WriteLine(line);
57 |
58 | protected override void ClosePort()
59 | {
60 | if (Port is null)
61 | {
62 | return;
63 | }
64 |
65 | Port.Close();
66 | Port.Dispose();
67 | Port = null;
68 | }
69 |
70 | private static System.IO.Ports.Parity ConvertParity(Parity parity) => parity switch
71 | {
72 | Parity.Even => System.IO.Ports.Parity.Even,
73 | Parity.Mark => System.IO.Ports.Parity.Mark,
74 | Parity.None => System.IO.Ports.Parity.None,
75 | Parity.Odd => System.IO.Ports.Parity.Odd,
76 | Parity.Space => System.IO.Ports.Parity.Space,
77 | _ => throw new ArgumentOutOfRangeException(nameof(parity), parity, null)
78 | };
79 |
80 | private static System.IO.Ports.StopBits ConvertStopBits(StopBits stopBits) => stopBits switch
81 | {
82 | StopBits.NotSet => System.IO.Ports.StopBits.None,
83 | StopBits.One => System.IO.Ports.StopBits.One,
84 | StopBits.OnePointFive => System.IO.Ports.StopBits.OnePointFive,
85 | StopBits.Two => System.IO.Ports.StopBits.Two,
86 | _ => throw new ArgumentOutOfRangeException(nameof(stopBits), stopBits, null)
87 | };
88 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/app.css:
--------------------------------------------------------------------------------
1 | @import url('open-iconic/font/css/open-iconic-bootstrap.min.css');
2 |
3 | html, body {
4 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
5 | }
6 |
7 | h1:focus {
8 | outline: none;
9 | }
10 |
11 | a, .btn-link {
12 | color: #0071c1;
13 | }
14 |
15 | .btn-primary {
16 | color: #fff;
17 | background-color: #1b6ec2;
18 | border-color: #1861ac;
19 | }
20 |
21 | .content {
22 | padding-top: 1.1rem;
23 | }
24 |
25 | .valid.modified:not([type=checkbox]) {
26 | outline: 1px solid #26b050;
27 | }
28 |
29 | .invalid {
30 | outline: 1px solid red;
31 | }
32 |
33 | .validation-message {
34 | color: red;
35 | }
36 |
37 | #blazor-error-ui {
38 | background: lightyellow;
39 | bottom: 0;
40 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
41 | display: none;
42 | left: 0;
43 | padding: 0.6rem 1.25rem 0.7rem 1.25rem;
44 | position: fixed;
45 | width: 100%;
46 | z-index: 1000;
47 | }
48 |
49 | #blazor-error-ui .dismiss {
50 | cursor: pointer;
51 | position: absolute;
52 | right: 0.75rem;
53 | top: 0.5rem;
54 | }
55 |
56 | .blazor-error-boundary {
57 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
58 | padding: 1rem 1rem 1rem 3.7rem;
59 | color: white;
60 | }
61 |
62 | .blazor-error-boundary::after {
63 | content: "An error has occurred."
64 | }
65 |
66 | .status-bar-safe-area {
67 | display: none;
68 | }
69 |
70 | @supports (-webkit-touch-callout: none) {
71 | .status-bar-safe-area {
72 | display: flex;
73 | position: sticky;
74 | top: 0;
75 | height: env(safe-area-inset-top);
76 | background-color: #f7f7f7;
77 | width: 100%;
78 | z-index: 1;
79 | }
80 |
81 | .flex-column, .navbar-brand {
82 | padding-left: env(safe-area-inset-left);
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/SerialTerminal.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net7.0-maccatalyst;net6.0-android;net6.0-ios
5 | $(TargetFrameworks);net6.0-windows10.0.19041.0
6 |
7 |
8 | Exe
9 | SerialTerminal
10 | true
11 | true
12 | enable
13 | false
14 |
15 |
16 | SerialTerminal
17 |
18 |
19 | com.companyname.serialterminal
20 | 069F5ACF-1C1F-45FC-A8C0-F00F4221B42A
21 |
22 |
23 | 1.0
24 | 1
25 |
26 | 14.2
27 | 14.0
28 | 23.0
29 | 10.0.17763.0
30 | 10.0.17763.0
31 | 6.5
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/SerialPortAndroid.cs:
--------------------------------------------------------------------------------
1 | using Maui.Serial.Platforms.Android.Usb;
2 | using Microsoft.Extensions.Logging;
3 |
4 | namespace Maui.Serial.Platforms.Android;
5 |
6 | public class SerialPortAndroid : SerialPortBase
7 | {
8 | public SerialPortAndroid(string portName, SerialPortParameters parameters = null, ILogger logger = null) : base(portName, parameters, logger)
9 | {
10 | UsbSerialPort = SerialPortPlatform.GetUsbPortByName(portName);
11 | UsbSerialPort.Parameters = parameters ?? new SerialPortParameters();
12 | _pollingTask = new PollingTask(PollingAction);
13 | }
14 |
15 |
16 | private readonly List _readBuffer = new();
17 | private readonly PollingTask _pollingTask;
18 | private byte[] _pollingBuffer;
19 |
20 | protected internal UsbSerialPort UsbSerialPort { get; }
21 |
22 | protected override void OpenPort(string portName, SerialPortParameters parameters)
23 | {
24 | Close();
25 | UsbSerialPort.Parameters = parameters;
26 | UsbSerialPort.Open();
27 |
28 | var bufferSize = UsbSerialPort.Parameters.ReadBufferSize;
29 | _pollingBuffer = new byte[bufferSize];
30 | _pollingTask.Start();
31 | }
32 |
33 | protected override int ReadFromPort(byte[] data) => UsbSerialPort.Read(data);
34 |
35 | protected override string ReadLineFromPort()
36 | {
37 | var data = _readBuffer.ToArray();
38 | var separator = Parameters.Encoding.GetBytes(Parameters.NewLine);
39 |
40 | var index = Array.IndexOf(data, separator[0]);
41 | if (index < 0)
42 | {
43 | return string.Empty;
44 | }
45 |
46 | var len = index;
47 | if (separator.Length > 1)
48 | {
49 | if (index + 1 >= data.Length || data[index + 1] != separator[1])
50 | {
51 | return string.Empty;
52 | }
53 | len++;
54 | }
55 |
56 | var line = Parameters.Encoding.GetString(data, 0, index);
57 | _readBuffer.RemoveRange(0, len);
58 | return line;
59 | }
60 |
61 | protected override string ReadExistingFromPort()
62 | {
63 | ReadToBuffer();
64 | var data = _readBuffer.ToArray();
65 | _readBuffer.Clear();
66 | return Parameters.Encoding.GetString(data);
67 | }
68 |
69 | protected override void WriteToPort(byte[] data) => UsbSerialPort.Write(data);
70 |
71 | protected override void WriteToPort(string value) => WriteToPort(Parameters.Encoding.GetBytes(value));
72 |
73 | protected override void WriteLineToPort(string line) => WriteToPort(line + Parameters.NewLine);
74 |
75 | protected override void ClosePort()
76 | {
77 | _readBuffer.Clear();
78 | _pollingTask.Stop();
79 | UsbSerialPort.Close();
80 | }
81 |
82 | protected void ReadToBuffer()
83 | {
84 | try
85 | {
86 | var len = UsbSerialPort.Read(_pollingBuffer);
87 | if (len <= 0)
88 | {
89 | return;
90 | }
91 |
92 | _readBuffer.AddRange(_pollingBuffer.Take(len));
93 | OnDataReceived();
94 | }
95 | catch
96 | {
97 | OnErrorReceived();
98 | }
99 | }
100 |
101 | private void PollingAction(CancellationToken cancellation)
102 | {
103 | if (cancellation.IsCancellationRequested)
104 | {
105 | throw new TaskCanceledException();
106 | }
107 |
108 | ReadToBuffer();
109 | }
110 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/STM32/STM32UsbSerialPort.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Microsoft.Extensions.Logging;
4 | // ReSharper disable InconsistentNaming
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.STM32;
7 |
8 | public class STM32UsbSerialPortDriver : CommonUsbSerialPort
9 | {
10 | private const int USB_WRITE_TIMEOUT_MILLIS = 5000;
11 | private const int USB_RECIP_INTERFACE = 0x01;
12 | private const int USB_RT_AM = UsbConstants.UsbTypeClass | USB_RECIP_INTERFACE;
13 | private const int SET_LINE_CODING = 0x20;
14 | private const int SET_CONTROL_LINE_STATE = 0x22;
15 |
16 | private int _controlInterfaceIndex;
17 | private bool _rts;
18 | private bool _dtr;
19 |
20 | public STM32UsbSerialPortDriver(UsbManager manager, UsbDevice device, int portNumber, ILogger logger) :
21 | base(manager, device, portNumber, logger)
22 | {
23 | }
24 |
25 | public override bool GetCD() => false;
26 | public override bool GetCTS() => false;
27 | public override bool GetDSR() => false;
28 | public override bool GetDTR() => _dtr;
29 | public override void SetDTR(bool value)
30 | {
31 | _dtr = value;
32 | SetDtrRts();
33 | }
34 | public override bool GetRI() => false;
35 | public override bool GetRTS() => _rts;
36 | public override void SetRTS(bool value)
37 | {
38 | _rts = value;
39 | SetDtrRts();
40 | }
41 |
42 | protected override void SetInterfaces(UsbDevice device)
43 | {
44 | var (_, ctrlIndex) = FindInterface(device, x => x.InterfaceClass == UsbClass.Comm);
45 | var (dataInterface, _) = FindInterface(device, x => x.InterfaceClass == UsbClass.CdcData);
46 | SetReadEndPoint(dataInterface.GetEndpoint(1));
47 | SetWriteEndPoint(dataInterface.GetEndpoint(0));
48 |
49 | _controlInterfaceIndex = ctrlIndex;
50 | }
51 |
52 | protected override void SetParameters(UsbDeviceConnection connection, SerialPortParameters parameters)
53 | {
54 | byte stopBitsBytes = parameters.StopBits switch
55 | {
56 | StopBits.One => 0,
57 | StopBits.OnePointFive => 1,
58 | StopBits.Two => 2,
59 | _ => throw new ArgumentException($"Bad value for stopBits: {parameters.StopBits}")
60 | };
61 |
62 | byte parityBitesBytes = parameters.Partity switch
63 | {
64 | Parity.None => 0,
65 | Parity.Odd => 1,
66 | Parity.Even => 2,
67 | Parity.Mark => 3,
68 | Parity.Space => 4,
69 | _ => throw new ArgumentException($"Bad value for parity: {parameters.Partity}")
70 | };
71 |
72 | var baudRate = parameters.BaudRate;
73 |
74 | byte[] msg =
75 | {
76 | (byte)(baudRate & 0xff),
77 | (byte)(baudRate >> 8 & 0xff),
78 | (byte)(baudRate >> 16 & 0xff),
79 | (byte)(baudRate >> 24 & 0xff),
80 | stopBitsBytes,
81 | parityBitesBytes,
82 | (byte)parameters.DataBits
83 | };
84 | SendAcmControlMessage(SET_LINE_CODING, 0, msg);
85 | }
86 |
87 | [DebuggerStepThrough]
88 | private void SetDtrRts()
89 | {
90 | var value = (_rts ? 0x2 : 0) | (_dtr ? 0x1 : 0);
91 | SendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
92 | }
93 |
94 | [DebuggerStepThrough]
95 | private void SendAcmControlMessage(int request, int value, byte[] buf) =>
96 | UsbConnection.ControlTransfer((UsbAddressing)USB_RT_AM, request, value, _controlInterfaceIndex, buf, buf?.Length ?? 0, USB_WRITE_TIMEOUT_MILLIS);
97 | }
98 |
99 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Usb/UsbDeviceProber.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Concurrent;
2 | using System.Diagnostics;
3 | using System.Reflection;
4 | using Android.Hardware.Usb;
5 | using Java.Lang;
6 | using Java.Lang.Reflect;
7 | using Microsoft.Extensions.Logging;
8 |
9 | namespace Maui.Serial.Platforms.Android.Usb;
10 |
11 | internal class UsbDeviceProber
12 | {
13 | public UsbDeviceProber(ILogger logger = null)
14 | {
15 | Logger = logger;
16 | }
17 |
18 | public ILogger Logger { get; }
19 |
20 | public IDictionary Drivers { get; } =
21 | new ConcurrentDictionary();
22 |
23 | public void RegisterDriver(UsbDeviceDriverId driverId, Type driverType)
24 | {
25 | if (Drivers.ContainsKey(driverId))
26 | {
27 | return;
28 | }
29 |
30 | Drivers.Add(driverId, driverType);
31 | }
32 |
33 | [DebuggerStepThrough]
34 | public void RegisterDriver(IEnumerable driverIds, Type driverType)
35 | {
36 | foreach (var driverId in driverIds)
37 | {
38 | RegisterDriver(driverId, driverType);
39 | }
40 | }
41 |
42 | public void RegisterDriver(Type driverType)
43 | {
44 | var attributes = driverType.GetCustomAttributes().ToArray();
45 | if (!attributes.Any())
46 | {
47 | throw new ArgumentException($"{driverType.FullName} has no UsbDeviceDriverAttribute");
48 | }
49 |
50 | foreach (var attribute in attributes)
51 | {
52 | RegisterDriver(attribute.DriverIds, driverType);
53 | }
54 | }
55 |
56 | public void RegisterDriver(Assembly assembly)
57 | {
58 | var driverTypes = assembly.GetTypes()
59 | .Where(x => x.IsSubclassOf(typeof(UsbDeviceDriver)) && !x.IsAbstract).ToArray();
60 |
61 | foreach (var driverType in driverTypes)
62 | {
63 | RegisterDriver(driverType);
64 | }
65 | }
66 |
67 | [DebuggerStepThrough]
68 | public IEnumerable Scan(UsbManager usbManager) => usbManager.DeviceList
69 | ?.Select(device => ProbeDevice(usbManager, device.Value)).Where(driver => driver is not null);
70 |
71 | public UsbDeviceDriver ProbeDevice(UsbManager usbManager, UsbDevice usbDevice)
72 | {
73 | usbManager.RequestPermission(usbDevice);
74 |
75 | var vendorId = usbDevice.VendorId;
76 | var productId = usbDevice.ProductId;
77 |
78 | var driverKey = new UsbDeviceDriverId(vendorId, productId);
79 |
80 | if (!Drivers.TryGetValue(driverKey, out var driverType))
81 | {
82 | throw new NotSupportedException($"UsbDevice Driver {vendorId}/{productId} not found");
83 | }
84 |
85 | try
86 | {
87 | return (UsbDeviceDriver)Activator.CreateInstance(driverType, usbManager, usbDevice, Logger);
88 | }
89 | catch (NoSuchMethodException e)
90 | {
91 | throw new RuntimeException(e);
92 | }
93 | catch (IllegalArgumentException e)
94 | {
95 | throw new RuntimeException(e);
96 | }
97 | catch (InstantiationException e)
98 | {
99 | throw new RuntimeException(e);
100 | }
101 | catch (IllegalAccessException e)
102 | {
103 | throw new RuntimeException(e);
104 | }
105 | catch (InvocationTargetException e)
106 | {
107 | throw new RuntimeException(e);
108 | }
109 | }
110 |
111 | }
--------------------------------------------------------------------------------
/src/Maui.Serial/SerialPortBase.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Microsoft.Extensions.Logging;
3 |
4 | namespace Maui.Serial;
5 |
6 | public abstract class SerialPortBase : ISerialPort
7 | {
8 | protected SerialPortBase(string portName, SerialPortParameters parameters = null, ILogger logger = null)
9 | {
10 | PortName = portName;
11 | Parameters = parameters ?? new SerialPortParameters();
12 | IsOpen = false;
13 | }
14 |
15 | public string PortName { get; }
16 |
17 | public SerialPortParameters Parameters { get; private set; }
18 |
19 | public bool IsOpen { get; private set; }
20 |
21 | public virtual void Open(SerialPortParameters parameters)
22 | {
23 | if (IsOpen)
24 | {
25 | return;
26 | }
27 |
28 | if (parameters is not null)
29 | {
30 | Parameters = parameters;
31 | }
32 |
33 | OpenPort(PortName, Parameters);
34 | IsOpen = true;
35 | }
36 |
37 | public virtual int Read(byte[] data)
38 | {
39 | EnsurePortIsOpen();
40 | return ReadFromPort(data);
41 | }
42 |
43 | public virtual string ReadLine()
44 | {
45 | EnsurePortIsOpen();
46 | return ReadLineFromPort();
47 | }
48 |
49 | public virtual string ReadExisting()
50 | {
51 | EnsurePortIsOpen();
52 | return ReadExistingFromPort();
53 | }
54 |
55 | public virtual void Write(byte[] data)
56 | {
57 | EnsurePortIsOpen();
58 | WriteToPort(data);
59 | }
60 |
61 | public virtual void Write(string value)
62 | {
63 | EnsurePortIsOpen();
64 | WriteToPort(value);
65 | }
66 |
67 | public virtual void WriteLine(string line)
68 | {
69 | EnsurePortIsOpen();
70 | WriteLineToPort(line);
71 | }
72 |
73 | public virtual void Close()
74 | {
75 | if (!IsOpen)
76 | {
77 | return;
78 | }
79 |
80 | ClosePort();
81 | IsOpen = false;
82 | }
83 |
84 | public virtual void Dispose()
85 | {
86 | Close();
87 | GC.SuppressFinalize(this);
88 | }
89 |
90 | public event EventHandler DataReceived;
91 |
92 | public event EventHandler ErrorReceived;
93 |
94 | protected abstract void OpenPort(string portName, SerialPortParameters parameters);
95 |
96 | protected abstract void ClosePort();
97 |
98 | protected virtual void EnsurePortIsOpen()
99 | {
100 | if (!IsOpen)
101 | {
102 | throw new InvalidOperationException("Serial port is not open.");
103 | }
104 | }
105 |
106 | [DebuggerStepThrough]
107 | protected abstract int ReadFromPort(byte[] data);
108 |
109 | [DebuggerStepThrough]
110 | protected abstract string ReadLineFromPort();
111 |
112 | [DebuggerStepThrough]
113 | protected abstract string ReadExistingFromPort();
114 |
115 | [DebuggerStepThrough]
116 | protected abstract void WriteToPort(byte[] data);
117 |
118 | [DebuggerStepThrough]
119 | protected abstract void WriteToPort(string value);
120 |
121 | [DebuggerStepThrough]
122 | protected abstract void WriteLineToPort(string line);
123 |
124 | protected void OnDataReceived(SerialDataEventType eventType = SerialDataEventType.Chars) =>
125 | DataReceived?.Invoke(this, new SerialPortDataReceivedEventArgs(eventType));
126 |
127 | protected void OnErrorReceived(SerialPortError error = SerialPortError.Frame) =>
128 | ErrorReceived?.Invoke(this, new SerialPortErrorEventArgs(error));
129 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/README.md:
--------------------------------------------------------------------------------
1 | [Open Iconic v1.1.1](https://github.com/iconic/open-iconic)
2 | ===========
3 |
4 | ### Open Iconic is the open source sibling of [Iconic](https://github.com/iconic/open-iconic). It is a hyper-legible collection of 223 icons with a tiny footprint—ready to use with Bootstrap and Foundation. [View the collection](https://github.com/iconic/open-iconic)
5 |
6 |
7 |
8 | ## What's in Open Iconic?
9 |
10 | * 223 icons designed to be legible down to 8 pixels
11 | * Super-light SVG files - 61.8 for the entire set
12 | * SVG sprite—the modern replacement for icon fonts
13 | * Webfont (EOT, OTF, SVG, TTF, WOFF), PNG and WebP formats
14 | * Webfont stylesheets (including versions for Bootstrap and Foundation) in CSS, LESS, SCSS and Stylus formats
15 | * PNG and WebP raster images in 8px, 16px, 24px, 32px, 48px and 64px.
16 |
17 |
18 | ## Getting Started
19 |
20 | #### For code samples and everything else you need to get started with Open Iconic, check out our [Icons](https://github.com/iconic/open-iconic) and [Reference](https://github.com/iconic/open-iconic) sections.
21 |
22 | ### General Usage
23 |
24 | #### Using Open Iconic's SVGs
25 |
26 | We like SVGs and we think they're the way to display icons on the web. Since Open Iconic are just basic SVGs, we suggest you display them like you would any other image (don't forget the `alt` attribute).
27 |
28 | ```
29 |
30 | ```
31 |
32 | #### Using Open Iconic's SVG Sprite
33 |
34 | Open Iconic also comes in a SVG sprite which allows you to display all the icons in the set with a single request. It's like an icon font, without being a hack.
35 |
36 | Adding an icon from an SVG sprite is a little different than what you're used to, but it's still a piece of cake. *Tip: To make your icons easily style able, we suggest adding a general class to the* `` *tag and a unique class name for each different icon in the* `` *tag.*
37 |
38 | ```
39 |
40 |
41 |
42 | ```
43 |
44 | Sizing icons only needs basic CSS. All the icons are in a square format, so just set the `` tag with equal width and height dimensions.
45 |
46 | ```
47 | .icon {
48 | width: 16px;
49 | height: 16px;
50 | }
51 | ```
52 |
53 | Coloring icons is even easier. All you need to do is set the `fill` rule on the `` tag.
54 |
55 | ```
56 | .icon-account-login {
57 | fill: #f00;
58 | }
59 | ```
60 |
61 | To learn more about SVG Sprites, read [Chris Coyier's guide](http://css-tricks.com/svg-sprites-use-better-icon-fonts/).
62 |
63 | #### Using Open Iconic's Icon Font...
64 |
65 |
66 | ##### …with Bootstrap
67 |
68 | You can find our Bootstrap stylesheets in `font/css/open-iconic-bootstrap.{css, less, scss, styl}`
69 |
70 |
71 | ```
72 |
73 | ```
74 |
75 |
76 | ```
77 |
78 | ```
79 |
80 | ##### …with Foundation
81 |
82 | You can find our Foundation stylesheets in `font/css/open-iconic-foundation.{css, less, scss, styl}`
83 |
84 | ```
85 |
86 | ```
87 |
88 |
89 | ```
90 |
91 | ```
92 |
93 | ##### …on its own
94 |
95 | You can find our default stylesheets in `font/css/open-iconic.{css, less, scss, styl}`
96 |
97 | ```
98 |
99 | ```
100 |
101 | ```
102 |
103 | ```
104 |
105 |
106 | ## License
107 |
108 | ### Icons
109 |
110 | All code (including SVG markup) is under the [MIT License](http://opensource.org/licenses/MIT).
111 |
112 | ### Fonts
113 |
114 | All fonts are under the [SIL Licensed](http://scripts.sil.org/cms/scripts/page.php?item_id=OFL_web).
115 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/FONT-LICENSE:
--------------------------------------------------------------------------------
1 | SIL OPEN FONT LICENSE Version 1.1
2 |
3 | Copyright (c) 2014 Waybury
4 |
5 | PREAMBLE
6 | The goals of the Open Font License (OFL) are to stimulate worldwide
7 | development of collaborative font projects, to support the font creation
8 | efforts of academic and linguistic communities, and to provide a free and
9 | open framework in which fonts may be shared and improved in partnership
10 | with others.
11 |
12 | The OFL allows the licensed fonts to be used, studied, modified and
13 | redistributed freely as long as they are not sold by themselves. The
14 | fonts, including any derivative works, can be bundled, embedded,
15 | redistributed and/or sold with any software provided that any reserved
16 | names are not used by derivative works. The fonts and derivatives,
17 | however, cannot be released under any other type of license. The
18 | requirement for fonts to remain under this license does not apply
19 | to any document created using the fonts or their derivatives.
20 |
21 | DEFINITIONS
22 | "Font Software" refers to the set of files released by the Copyright
23 | Holder(s) under this license and clearly marked as such. This may
24 | include source files, build scripts and documentation.
25 |
26 | "Reserved Font Name" refers to any names specified as such after the
27 | copyright statement(s).
28 |
29 | "Original Version" refers to the collection of Font Software components as
30 | distributed by the Copyright Holder(s).
31 |
32 | "Modified Version" refers to any derivative made by adding to, deleting,
33 | or substituting -- in part or in whole -- any of the components of the
34 | Original Version, by changing formats or by porting the Font Software to a
35 | new environment.
36 |
37 | "Author" refers to any designer, engineer, programmer, technical
38 | writer or other person who contributed to the Font Software.
39 |
40 | PERMISSION & CONDITIONS
41 | Permission is hereby granted, free of charge, to any person obtaining
42 | a copy of the Font Software, to use, study, copy, merge, embed, modify,
43 | redistribute, and sell modified and unmodified copies of the Font
44 | Software, subject to the following conditions:
45 |
46 | 1) Neither the Font Software nor any of its individual components,
47 | in Original or Modified Versions, may be sold by itself.
48 |
49 | 2) Original or Modified Versions of the Font Software may be bundled,
50 | redistributed and/or sold with any software, provided that each copy
51 | contains the above copyright notice and this license. These can be
52 | included either as stand-alone text files, human-readable headers or
53 | in the appropriate machine-readable metadata fields within text or
54 | binary files as long as those fields can be easily viewed by the user.
55 |
56 | 3) No Modified Version of the Font Software may use the Reserved Font
57 | Name(s) unless explicit written permission is granted by the corresponding
58 | Copyright Holder. This restriction only applies to the primary font name as
59 | presented to the users.
60 |
61 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
62 | Software shall not be used to promote, endorse or advertise any
63 | Modified Version, except to acknowledge the contribution(s) of the
64 | Copyright Holder(s) and the Author(s) or with their explicit written
65 | permission.
66 |
67 | 5) The Font Software, modified or unmodified, in part or in whole,
68 | must be distributed entirely under this license, and must not be
69 | distributed under any other license. The requirement for fonts to
70 | remain under this license does not apply to any document created
71 | using the Font Software.
72 |
73 | TERMINATION
74 | This license becomes null and void if any of the above conditions are
75 | not met.
76 |
77 | DISCLAIMER
78 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
79 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
80 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
81 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
82 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
83 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
84 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
85 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
86 | OTHER DEALINGS IN THE FONT SOFTWARE.
87 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Cp21xx/Cp21xxUsbSerialPortDriver.cs:
--------------------------------------------------------------------------------
1 | using Android.Hardware.Usb;
2 | using Maui.Serial.Platforms.Android.Usb;
3 | using Microsoft.Extensions.Logging;
4 | // ReSharper disable InconsistentNaming
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.Cp21xx;
7 |
8 | public class Cp21xxUsbSerialPort : CommonUsbSerialPort
9 | {
10 | private const int DEFAULT_BAUD_RATE = 9600;
11 | private const int USB_WRITE_TIMEOUT_MILLIS = 5000;
12 | private const int REQTYPE_HOST_TO_DEVICE = 0x41;
13 | private const int REQTYPE_DEVICE_TO_HOST = 0xc1;
14 | private const int SILABSER_IFC_ENABLE_REQUEST_CODE = 0x00;
15 | private const int SILABSER_SET_BAUDDIV_REQUEST_CODE = 0x01;
16 | private const int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03;
17 | private const int SILABSER_SET_MHS_REQUEST_CODE = 0x07;
18 | private const int SILABSER_SET_BAUDRATE = 0x1E;
19 | private const int GET_MODEM_STATUS_REQUEST = 0x08;
20 | private const int MODEM_STATUS_CTS = 0x10;
21 | private const int MODEM_STATUS_DSR = 0x20;
22 | private const int MODEM_STATUS_RI = 0x40;
23 | private const int MODEM_STATUS_CD = 0x80;
24 | private const int UART_ENABLE = 0x0001;
25 | private const int BAUD_RATE_GEN_FREQ = 0x384000;
26 | private const int MCR_DTR = 0x0001;
27 | private const int MCR_RTS = 0x0002;
28 | private const int MCR_ALL = 0x0003;
29 | private const int CONTROL_WRITE_DTR = 0x0100;
30 | private const int CONTROL_WRITE_RTS = 0x0200;
31 |
32 | public Cp21xxUsbSerialPort(UsbManager manager, UsbDevice device, int portNumber, ILogger logger) : base(manager, device, portNumber, logger)
33 | {
34 | }
35 |
36 | protected override void SetInterfaces(UsbDevice device)
37 | {
38 | var dataIface = GetInterfaceByIndex(device,device.InterfaceCount - 1);
39 |
40 | for (var i = 0; i < dataIface.EndpointCount; i++)
41 | {
42 | var ep = dataIface.GetEndpoint(i);
43 | if (ep?.Type != (UsbAddressing)UsbSupport.UsbEndpointXferBulk)
44 | {
45 | continue;
46 | }
47 |
48 | if (ep.Direction == (UsbAddressing)UsbSupport.UsbDirIn)
49 | {
50 | SetReadEndPoint(ep);
51 | }
52 | else
53 | {
54 | SetWriteEndPoint(ep);
55 | }
56 | }
57 |
58 | SetConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
59 | SetConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
60 | SetConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
61 | }
62 |
63 | protected override void SetParameters(UsbDeviceConnection connection, SerialPortParameters parameters)
64 | {
65 | SetBaudRate(parameters.BaudRate);
66 |
67 | var configDataBits = 0;
68 | configDataBits |= parameters.DataBits switch
69 | {
70 | DataBits.Bits5 => 0x0500,
71 | DataBits.Bits6 => 0x0600,
72 | DataBits.Bits7 => 0x0700,
73 | DataBits.Bits8 => 0x0800,
74 | _ => 0x0800
75 | };
76 |
77 | switch (parameters.Partity)
78 | {
79 | case Parity.Odd:
80 | configDataBits |= 0x0010;
81 | break;
82 | case Parity.Even:
83 | configDataBits |= 0x0020;
84 | break;
85 | case Parity.None:
86 | break;
87 | case Parity.Mark:
88 | break;
89 | case Parity.Space:
90 | break;
91 | default:
92 | throw new ArgumentOutOfRangeException(nameof(parameters.Partity), parameters.Partity, null);
93 | }
94 |
95 | switch (parameters.StopBits)
96 | {
97 | case StopBits.One:
98 | configDataBits |= 0;
99 | break;
100 | case StopBits.Two:
101 | configDataBits |= 2;
102 | break;
103 | case StopBits.OnePointFive:
104 | break;
105 | case StopBits.NotSet:
106 | break;
107 | default:
108 | throw new ArgumentOutOfRangeException(nameof(parameters.StopBits), parameters.StopBits, null);
109 | }
110 | SetConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
111 | }
112 |
113 |
114 | public override bool GetCD() => (GetStatus() & MODEM_STATUS_CD) != 0;
115 | public override bool GetCTS() => (GetStatus() & MODEM_STATUS_CTS) != 0;
116 | public override bool GetDSR() => (GetStatus() & MODEM_STATUS_DSR) != 0;
117 | public override bool GetDTR() => (GetStatus() & MCR_DTR) != 0;
118 | public override void SetDTR(bool value) =>
119 | SetConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, (value ? MCR_DTR : 0) | CONTROL_WRITE_DTR);
120 |
121 | public override bool GetRI() => (GetStatus() & MODEM_STATUS_RI) != 0;
122 |
123 | public override bool GetRTS() => (GetStatus() & MCR_RTS) != 0;
124 |
125 | public override void SetRTS(bool value) =>
126 | SetConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, (value ? MCR_RTS : 0) | CONTROL_WRITE_RTS);
127 |
128 |
129 | private int GetStatus()
130 | {
131 | var data = new byte[1];
132 | var result = UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_DEVICE_TO_HOST, GET_MODEM_STATUS_REQUEST,
133 | 0, 0, data, data.Length, USB_WRITE_TIMEOUT_MILLIS);
134 | if (result != 1)
135 | {
136 | throw new IOException("Get modem status failed: result=" + result);
137 | }
138 |
139 | return data[0];
140 | }
141 |
142 | private void SetBaudRate(int baudRate)
143 | {
144 | var data = new[]
145 | {
146 | (byte)(baudRate & 0xff),
147 | (byte)((baudRate >> 8) & 0xff),
148 | (byte)((baudRate >> 16) & 0xff),
149 | (byte)((baudRate >> 24) & 0xff)
150 | };
151 | var ret = UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
152 | 0, 0, data, 4, USB_WRITE_TIMEOUT_MILLIS);
153 | if (ret < 0)
154 | {
155 | throw new IOException("Error setting baud rate.");
156 | }
157 | }
158 |
159 |
160 | private void SetConfigSingle(int request, int value) =>
161 | UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_HOST_TO_DEVICE, request, value,
162 | 0, null, 0, USB_WRITE_TIMEOUT_MILLIS);
163 | }
164 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/CommonUsbSerialPort.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Maui.Serial.Platforms.Android.Usb;
4 | using Microsoft.Extensions.Logging;
5 |
6 | // ReSharper disable InconsistentNaming
7 | namespace Maui.Serial.Platforms.Android.Drivers;
8 |
9 | public abstract class CommonUsbSerialPort : UsbSerialPort
10 | {
11 | private readonly object _readBufferLock = new();
12 | private readonly object _writeBufferLock = new();
13 | private byte[] _readBuffer = Array.Empty();
14 | private byte[] _writeBuffer = Array.Empty();
15 |
16 | protected CommonUsbSerialPort(UsbManager manager, UsbDevice device, int portNumber, ILogger logger) :
17 | base(manager, device, portNumber, logger)
18 | {
19 | }
20 |
21 | protected UsbEndpoint ReadEndPoint { get; private set; }
22 | protected UsbEndpoint WriteEndPoint { get; private set; }
23 |
24 | public override void Open()
25 | {
26 | if (IsOpen)
27 | {
28 | return;
29 | }
30 |
31 | var connection = OpenConnection();
32 | UsbConnection = connection;
33 | SetParameters(connection, Parameters);
34 | SetInterfaces(UsbDevice);
35 |
36 | lock (_readBufferLock)
37 | {
38 | _readBuffer = new byte[Parameters.ReadBufferSize];
39 | }
40 |
41 | lock (_writeBufferLock)
42 | {
43 | _writeBuffer = new byte[Parameters.WriteBufferSize];
44 | }
45 | }
46 |
47 | public override void Close()
48 | {
49 | if (!IsOpen)
50 | {
51 | return;
52 | }
53 |
54 | CloseConnection();
55 | }
56 |
57 | public override int Read(byte[] dest) => ReadBufferFromDevice(dest.Length);
58 |
59 | public override int Write(byte[] src) => WriteBufferToDevice(src.Length);
60 |
61 | protected void SetReadEndPoint(UsbEndpoint usbEndpoint)
62 | {
63 | lock (_readBufferLock)
64 | {
65 | ReadEndPoint = usbEndpoint;
66 | }
67 | }
68 |
69 | protected void SetWriteEndPoint(UsbEndpoint usbEndpoint)
70 | {
71 | lock (_readBufferLock)
72 | {
73 | WriteEndPoint = usbEndpoint;
74 | }
75 | }
76 |
77 | protected virtual int ReadBufferFromDevice(int len)
78 | {
79 | var result = new List();
80 |
81 | var toRead = len;
82 | while (toRead > 0)
83 | {
84 | var buffer = new byte[len];
85 | var read = ReadFromDevice(buffer);
86 | if (read > 0)
87 | {
88 | toRead -= read;
89 | result.AddRange(buffer);
90 | continue;
91 | }
92 |
93 | break;
94 | }
95 |
96 | return CopyToReadBuffer(result.ToArray(), _readBuffer);
97 | }
98 |
99 | protected virtual int WriteBufferToDevice(int len)
100 | {
101 | int offset;
102 | for (offset = 0; offset < len;)
103 | {
104 |
105 | var buffer = CopyFromWriteBuffer(_writeBuffer, offset, len);
106 | var written = WriteToDevice(buffer);
107 | offset += written;
108 |
109 | }
110 |
111 | return offset;
112 | }
113 |
114 | protected virtual int ReadFromDevice(byte[] buffer)
115 | {
116 | var len = Math.Min(buffer.Length, Parameters.ReadBufferSize);
117 | lock (_readBufferLock)
118 | {
119 | len = UsbConnection.BulkTransfer(ReadEndPoint, _readBuffer, len, Parameters.ReadTimeout);
120 | if (len > 0)
121 | {
122 | Buffer.BlockCopy(_readBuffer, 0, buffer, 0, len);
123 | }
124 | }
125 |
126 | return len;
127 | }
128 |
129 | protected virtual int WriteToDevice(byte[] buffer)
130 | {
131 | var len = Math.Min(buffer.Length, Parameters.ReadBufferSize);
132 | lock (_writeBufferLock)
133 | {
134 | len = UsbConnection.BulkTransfer(WriteEndPoint, buffer, len, Parameters.WriteTimeout);
135 | if (len > 0)
136 | {
137 | Buffer.BlockCopy(_readBuffer, 0, buffer, 0, len);
138 | }
139 | }
140 |
141 | return len;
142 | }
143 |
144 | protected virtual int CopyToReadBuffer(byte[] source, byte[] destination)
145 | {
146 | Array.Copy(source, destination, source.Length);
147 | return source.Length;
148 | }
149 |
150 | protected virtual byte[] CopyFromWriteBuffer(byte[] source, int offset, int length)
151 | {
152 | var toWrite = length - offset;
153 | var buffer = new byte[toWrite];
154 | Buffer.BlockCopy(source, offset, buffer, 0, toWrite);
155 | return buffer;
156 | }
157 |
158 | protected virtual void CloseConnection()
159 | {
160 | UsbConnection.Close();
161 | UsbConnection = null;
162 | }
163 |
164 | protected (UsbInterface Interface, int Index) FindInterface(UsbDevice device, Func filter)
165 | {
166 | for (var index = 0; index < device.InterfaceCount; index++)
167 | {
168 | var usbInterface = device.GetInterface(index);
169 | if (!filter(usbInterface))
170 | {
171 | continue;
172 | }
173 |
174 | if (ClaimInterface(usbInterface))
175 | {
176 | return (usbInterface, index);
177 | }
178 |
179 | throw new UsbSerialRuntimeException($"Error during claim usb interface {usbInterface}");
180 | }
181 |
182 | return (null, -1);
183 | }
184 |
185 | protected UsbInterface GetInterfaceByIndex(UsbDevice device, int index)
186 | {
187 | var usbInterface = device.GetInterface(index);
188 |
189 | if (ClaimInterface(usbInterface))
190 | {
191 | return usbInterface;
192 | }
193 |
194 | throw new UsbSerialRuntimeException($"Error during claim usb interface {usbInterface}");
195 | }
196 |
197 | [DebuggerStepThrough]
198 | protected virtual bool ClaimInterface(UsbInterface usbInterface) =>
199 | UsbConnection.ClaimInterface(usbInterface, true);
200 |
201 | [DebuggerStepThrough]
202 | protected abstract void SetInterfaces(UsbDevice device);
203 |
204 | [DebuggerStepThrough]
205 | protected abstract void SetParameters(UsbDeviceConnection connection, SerialPortParameters parameters);
206 |
207 | [DebuggerStepThrough]
208 | protected virtual int ControlTransfer(UsbAddressing requestType, int request, int value, int index,
209 | byte[] buffer = null, int length = -1, int timeout = -1) =>
210 | UsbConnection.ControlTransfer(requestType, request, value, index, buffer, length, timeout);
211 | }
212 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/CdcAcm/CdcAcmUsbSerialPort.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Java.Lang;
4 | using Microsoft.Extensions.Logging;
5 | using IOException = Java.IO.IOException;
6 | // ReSharper disable InconsistentNaming
7 |
8 | namespace Maui.Serial.Platforms.Android.Drivers.CdcAcm;
9 |
10 | public class CdcAcmUsbSerialPort : CommonUsbSerialPort
11 | {
12 | #region Consts
13 | private const int SET_LINE_CODING = 0x20;
14 | private const int SET_CONTROL_LINE_STATE = 0x22;
15 | #endregion
16 |
17 | #region Fields
18 | private UsbInterface _controlInterface;
19 | private UsbInterface _dataInterface;
20 | private UsbEndpoint _controlEndpoint;
21 |
22 | private bool _rts;
23 | private bool _dtr;
24 | #endregion
25 |
26 | public CdcAcmUsbSerialPort(UsbManager manager, UsbDevice device, int portNumber, ILogger logger) : base(manager, device, portNumber, logger)
27 | {
28 | }
29 |
30 | public override bool GetCD() => false;
31 |
32 | public override bool GetCTS() => false;
33 |
34 | public override bool GetDSR() => false;
35 |
36 | public override bool GetDTR() => _dtr;
37 |
38 | public override void SetDTR(bool value)
39 | {
40 | _dtr = value;
41 | SetDtrRts();
42 | }
43 |
44 | public override bool GetRI() => false;
45 |
46 | public override bool GetRTS() => _rts;
47 |
48 | public override void SetRTS(bool value)
49 | {
50 | _rts = value;
51 | SetDtrRts();
52 | }
53 | protected override void SetInterfaces(UsbDevice device)
54 | {
55 | if (device.InterfaceCount == 1)
56 | {
57 | OpenSingleInterface(device);
58 | }
59 | else
60 | {
61 | OpenInterface(device);
62 | }
63 | }
64 |
65 | protected override void SetParameters(UsbDeviceConnection connection, SerialPortParameters parameters)
66 | {
67 | byte stopBitsByte = parameters.StopBits switch
68 | {
69 | StopBits.One => 0,
70 | StopBits.OnePointFive => 1,
71 | StopBits.Two => 2,
72 | _ => throw new IllegalArgumentException($"Bad value for stopBits: {parameters.StopBits}")
73 | };
74 |
75 | byte parityBitesByte = parameters.Partity switch
76 | {
77 | Parity.None => 0,
78 | Parity.Odd => 1,
79 | Parity.Even => 2,
80 | Parity.Mark => 3,
81 | Parity.Space => 4,
82 | _ => throw new IllegalArgumentException($"Bad value for parity: {parameters.Partity}")
83 | };
84 |
85 | var baudRate = parameters.BaudRate;
86 | byte[] msg =
87 | {
88 | (byte)(baudRate & 0xff),
89 | (byte)((baudRate >> 8) & 0xff),
90 | (byte)((baudRate >> 16) & 0xff),
91 | (byte)((baudRate >> 24) & 0xff),
92 | stopBitsByte,
93 | parityBitesByte,
94 | (byte)parameters.DataBits
95 | };
96 | SendAcmControlMessage(SET_LINE_CODING, 0, msg);
97 | }
98 |
99 | private void SetDtrRts()
100 | {
101 | var value = (_rts ? 0x2 : 0) | (_dtr ? 0x1 : 0);
102 | SendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null);
103 | }
104 |
105 | [DebuggerStepThrough]
106 | private void SendAcmControlMessage(int request, int value, byte[] buf) => UsbConnection.ControlTransfer((UsbAddressing)0x21, request, value, 0, buf, buf?.Length ?? 0, 5000);
107 |
108 | // ReSharper disable once CyclomaticComplexity
109 | private void OpenSingleInterface(UsbDevice device)
110 | {
111 | _controlInterface = GetInterfaceByIndex(device, 0);
112 | Logger?.LogDebug("Control iface={interface}", _controlInterface);
113 |
114 | _dataInterface = GetInterfaceByIndex(device, 0);
115 | Logger?.LogDebug("Control iface={interface}", _dataInterface);
116 |
117 |
118 | var endCount = _controlInterface.EndpointCount;
119 | if (endCount < 3)
120 | {
121 | Logger?.LogError("Not enough endpoints - need 3. count={endCount}", endCount);
122 | throw new IOException($"Insufficient number of endpoints({endCount})");
123 | }
124 |
125 | _controlEndpoint = null;
126 | for (var i = 0; i < endCount; ++i)
127 | {
128 | var ep = _controlInterface.GetEndpoint(i);
129 | switch (ep?.Direction)
130 | {
131 | case UsbAddressing.In when
132 | (ep.Type == UsbAddressing.XferInterrupt):
133 | Logger?.LogDebug("Found controlling endpoint");
134 | _controlEndpoint = ep;
135 | break;
136 | case UsbAddressing.In when
137 | (ep.Type == UsbAddressing.XferBulk):
138 | Logger?.LogDebug("Found reading endpoint");
139 | SetReadEndPoint(ep);
140 | break;
141 | case UsbAddressing.Out when
142 | ep.Type == UsbAddressing.XferBulk:
143 | Logger?.LogDebug("Found writing endpoint");
144 | SetWriteEndPoint(ep);
145 | break;
146 | case UsbAddressing.NumberMask:
147 | break;
148 | case UsbAddressing.XferBulk:
149 | break;
150 | case UsbAddressing.XferInterrupt:
151 | break;
152 | case UsbAddressing.XferIsochronous:
153 | break;
154 | case null:
155 | break;
156 | default:
157 | throw new InvalidDataException(ep.ToString());
158 | }
159 |
160 |
161 | if (_controlEndpoint is null ||
162 | ReadEndPoint is null ||
163 | WriteEndPoint is null)
164 | {
165 | continue;
166 | }
167 |
168 | Logger?.LogDebug("Found all required endpoints");
169 | return;
170 | }
171 |
172 |
173 | Logger?.LogError("Could not establish all endpoints");
174 | throw new IOException("Could not establish all endpoints");
175 | }
176 |
177 | private void OpenInterface(UsbDevice device)
178 | {
179 | Logger?.LogDebug("Claiming interfaces, count={count}", device.InterfaceCount);
180 |
181 | _controlInterface = GetInterfaceByIndex(device, 0);
182 | Logger?.LogDebug("Control iface={iface}", _controlInterface);
183 | _controlEndpoint = _controlInterface.GetEndpoint(0);
184 | Logger?.LogDebug("Control endpoint direction: {direction}", _controlEndpoint?.Direction);
185 | _dataInterface = GetInterfaceByIndex(device, 1);
186 | Logger?.LogDebug("Data iface={iface}", _dataInterface);
187 | SetReadEndPoint(_dataInterface.GetEndpoint(1));
188 | Logger?.LogDebug("Read endpoint direction: {direction}", ReadEndPoint?.Direction);
189 | SetWriteEndPoint(_dataInterface.GetEndpoint(0));
190 | Logger?.LogDebug("Write endpoint direction: {direction}", WriteEndPoint?.Direction);
191 | }
192 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Ch43x/Ch340UsbSerialPort.cs:
--------------------------------------------------------------------------------
1 | using Android.Hardware.Usb;
2 | using Maui.Serial.Platforms.Android.Usb;
3 | using Microsoft.Extensions.Logging;
4 | // ReSharper disable InconsistentNaming
5 |
6 | namespace Maui.Serial.Platforms.Android.Drivers.Ch43x;
7 |
8 | public class Ch340UsbSerialPortDriver : CommonUsbSerialPort
9 | {
10 | #region Consts
11 | private const int USB_TIMEOUT_MILLIS = 5000;
12 | private const int DEFAULT_BAUD_RATE = 9600;
13 |
14 | private const int SCL_DTR = 0x20;
15 | private const int SCL_RTS = 0x40;
16 | private const int LCR_ENABLE_RX = 0x80;
17 | private const int LCR_ENABLE_TX = 0x40;
18 | private const int LCR_STOP_BITS_2 = 0x04;
19 | private const int LCR_CS8 = 0x03;
20 | private const int LCR_CS7 = 0x02;
21 | private const int LCR_CS6 = 0x01;
22 | private const int LCR_CS5 = 0x00;
23 |
24 | private const int LCR_MARK_SPACE = 0x20;
25 | private const int LCR_PAR_EVEN = 0x10;
26 | private const int LCR_ENABLE_PAR = 0x08;
27 |
28 | private static readonly int[] _baudCodes = {
29 | 2400, 0xd901, 0x0038, 4800, 0x6402,
30 | 0x001f, 9600, 0xb202, 0x0013, 19200, 0xd902, 0x000d, 38400,
31 | 0x6403, 0x000a, 115200, 0xcc03, 0x0008
32 | };
33 | #endregion
34 |
35 | #region Fields
36 | private bool _dtr;
37 | private bool _rts;
38 | #endregion
39 |
40 | public Ch340UsbSerialPortDriver(UsbManager manager, UsbDevice device, int portNumber, ILogger logger) : base(manager, device, portNumber, logger)
41 | {
42 | }
43 |
44 | public override bool GetCD() => false;
45 | public override bool GetCTS() => false;
46 | public override bool GetDSR() => false;
47 | public override bool GetDTR() => _dtr;
48 | public override void SetDTR(bool value)
49 | {
50 | _dtr = value;
51 | SetControlLines();
52 | }
53 | public override bool GetRI() => false;
54 | public override bool GetRTS() => _rts;
55 | public override void SetRTS(bool value)
56 | {
57 | _rts = value;
58 | SetControlLines();
59 | }
60 |
61 | protected override void SetInterfaces(UsbDevice device)
62 | {
63 | var dataIface = UsbDevice.GetInterface(UsbDevice.InterfaceCount - 1);
64 |
65 | for (var i = 0; i < dataIface.EndpointCount; i++)
66 | {
67 | var ep = dataIface.GetEndpoint(i);
68 | if (ep?.Type != (UsbAddressing)UsbSupport.UsbEndpointXferBulk)
69 | {
70 | continue;
71 | }
72 |
73 | if (ep.Direction == (UsbAddressing)UsbSupport.UsbDirIn)
74 | {
75 | SetReadEndPoint(ep);
76 | continue;
77 | }
78 | SetWriteEndPoint(ep);
79 | }
80 | }
81 |
82 | protected override void SetParameters(UsbDeviceConnection connection, SerialPortParameters parameters)
83 | {
84 | Initialize();
85 | SetBaudRate(parameters.BaudRate);
86 |
87 | var lcr = LCR_ENABLE_RX | LCR_ENABLE_TX;
88 |
89 | lcr |= parameters.DataBits switch
90 | {
91 | DataBits.Bits5 => LCR_CS5,
92 | DataBits.Bits6 => LCR_CS6,
93 | DataBits.Bits7 => LCR_CS7,
94 | DataBits.Bits8 => LCR_CS8,
95 | _ => throw new Java.Lang.IllegalArgumentException($"Invalid data bits: {parameters.DataBits}"),
96 | };
97 |
98 | lcr |= parameters.Partity switch
99 | {
100 | Parity.None => lcr,
101 | Parity.Odd => LCR_ENABLE_PAR,
102 | Parity.Even => LCR_ENABLE_PAR | LCR_PAR_EVEN,
103 | Parity.Mark => LCR_ENABLE_PAR | LCR_MARK_SPACE,
104 | Parity.Space => LCR_ENABLE_PAR | LCR_MARK_SPACE | LCR_PAR_EVEN,
105 | _ => throw new Java.Lang.IllegalArgumentException($"Invalid parity: {parameters.Partity}"),
106 | };
107 |
108 | lcr |= parameters.StopBits switch
109 | {
110 | StopBits.One => lcr,
111 | StopBits.OnePointFive => throw new Java.Lang.UnsupportedOperationException("Unsupported stop bits: 1.5"),
112 | StopBits.Two => LCR_STOP_BITS_2,
113 | _ => throw new Java.Lang.IllegalArgumentException($"Invalid stop bits: {parameters.StopBits}")
114 | };
115 |
116 | var ret = ControlOut(0x9a, 0x2518, lcr);
117 | if (ret < 0)
118 | {
119 | throw new IOException("Error setting control byte");
120 | }
121 | }
122 | private int ControlOut(int request, int value, int index)
123 | {
124 | const int REQTYPE_HOST_TO_DEVICE = UsbConstants.UsbTypeVendor | UsbSupport.UsbDirOut;
125 | return UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_HOST_TO_DEVICE, request,
126 | value, index, null, 0, USB_TIMEOUT_MILLIS);
127 | }
128 |
129 | private int ControlIn(int request, int value, int index, byte[] buffer)
130 | {
131 | const int REQTYPE_HOST_TO_DEVICE = UsbConstants.UsbTypeVendor | UsbSupport.UsbDirIn;
132 | return UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_HOST_TO_DEVICE, request,
133 | value, index, buffer, buffer.Length, USB_TIMEOUT_MILLIS);
134 | }
135 |
136 | private void CheckState(string msg, int request, int value, IReadOnlyList expected)
137 | {
138 | var buffer = new byte[expected.Count];
139 | var ret = ControlIn(request, value, 0, buffer);
140 |
141 | if (ret < 0)
142 | {
143 | throw new IOException($"Failed send cmd [{msg}]");
144 | }
145 |
146 | if (ret != expected.Count)
147 | {
148 | throw new IOException($"Expected {expected.Count} bytes, but get {ret} [{msg}]");
149 | }
150 |
151 | for (var i = 0; i < expected.Count; i++)
152 | {
153 | if (expected[i] == -1)
154 | {
155 | continue;
156 | }
157 |
158 | var current = buffer[i] & 0xff;
159 | if (expected[i] != current)
160 | {
161 | throw new IOException($"Expected 0x{expected[i]:X} bytes, but get 0x{current:X} [ {msg} ]");
162 | }
163 | }
164 | }
165 |
166 | private void SetControlLines()
167 | {
168 | if (ControlOut(0xa4, ~((_dtr ? SCL_DTR : 0) | (_rts ? SCL_RTS : 0)), 0) < 0)
169 | {
170 | throw new IOException("Failed to set control lines");
171 | }
172 | }
173 |
174 | private void Initialize()
175 | {
176 | CheckState("init #1", 0x5f, 0, new[] { -1 /* 0x27, 0x30 */, 0x00 });
177 |
178 | if (ControlOut(0xa1, 0, 0) < 0)
179 | {
180 | throw new IOException("init failed! #2");
181 | }
182 |
183 | CheckState("init #4", 0x95, 0x2518, new[] { -1 /* 0x56, c3*/, 0x00 });
184 |
185 | if (ControlOut(0x9a, 0x2518, 0x0050) < 0)
186 | {
187 | throw new IOException("init failed! #5");
188 | }
189 |
190 | CheckState("init #6", 0x95, 0x0706, new[] { -1 /*0xf?*/, -1 /*0xec,0xee*/});
191 |
192 | if (ControlOut(0xa1, 0x501f, 0xd90a) < 0)
193 | {
194 | throw new IOException("init failed! #7");
195 | }
196 |
197 | SetControlLines();
198 | CheckState("init #10", 0x95, 0x0706, new[] { -1 /* 0x9f, 0xff*/, 0xee });
199 | }
200 |
201 | private void SetBaudRate(int baudRate)
202 | {
203 | for (var i = 0; i < _baudCodes.Length / 3; i++)
204 | {
205 | if (_baudCodes[i * 3] != baudRate)
206 | {
207 | continue;
208 | }
209 |
210 | var ret = ControlOut(0x9a, 0x1312, _baudCodes[i * 3 + 1]);
211 | if (ret < 0)
212 | {
213 | throw new IOException("Error setting baud rate. #1");
214 | }
215 |
216 | ret = ControlOut(0x9a, 0x0f2c, _baudCodes[i * 3 + 2]);
217 | if (ret < 0)
218 | {
219 | throw new IOException("Error setting baud rate. #1");
220 | }
221 |
222 | return;
223 | }
224 |
225 |
226 | throw new IOException("Baud rate " + baudRate + " currently not supported");
227 | }
228 | }
--------------------------------------------------------------------------------
/examples/SerialTerminal/wwwroot/css/open-iconic/font/css/open-iconic-bootstrap.min.css:
--------------------------------------------------------------------------------
1 | @font-face{font-family:Icons;src:url(../fonts/open-iconic.eot);src:url(../fonts/open-iconic.eot?#iconic-sm) format('embedded-opentype'),url(../fonts/open-iconic.woff) format('woff'),url(../fonts/open-iconic.ttf) format('truetype'),url(../fonts/open-iconic.otf) format('opentype'),url(../fonts/open-iconic.svg#iconic-sm) format('svg');font-weight:400;font-style:normal}.oi{position:relative;top:1px;display:inline-block;speak:none;font-family:Icons;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.oi:empty:before{width:1em;text-align:center;box-sizing:content-box}.oi.oi-align-center:before{text-align:center}.oi.oi-align-left:before{text-align:left}.oi.oi-align-right:before{text-align:right}.oi.oi-flip-horizontal:before{-webkit-transform:scale(-1,1);-ms-transform:scale(-1,1);transform:scale(-1,1)}.oi.oi-flip-vertical:before{-webkit-transform:scale(1,-1);-ms-transform:scale(-1,1);transform:scale(1,-1)}.oi.oi-flip-horizontal-vertical:before{-webkit-transform:scale(-1,-1);-ms-transform:scale(-1,1);transform:scale(-1,-1)}.oi-account-login:before{content:'\e000'}.oi-account-logout:before{content:'\e001'}.oi-action-redo:before{content:'\e002'}.oi-action-undo:before{content:'\e003'}.oi-align-center:before{content:'\e004'}.oi-align-left:before{content:'\e005'}.oi-align-right:before{content:'\e006'}.oi-aperture:before{content:'\e007'}.oi-arrow-bottom:before{content:'\e008'}.oi-arrow-circle-bottom:before{content:'\e009'}.oi-arrow-circle-left:before{content:'\e00a'}.oi-arrow-circle-right:before{content:'\e00b'}.oi-arrow-circle-top:before{content:'\e00c'}.oi-arrow-left:before{content:'\e00d'}.oi-arrow-right:before{content:'\e00e'}.oi-arrow-thick-bottom:before{content:'\e00f'}.oi-arrow-thick-left:before{content:'\e010'}.oi-arrow-thick-right:before{content:'\e011'}.oi-arrow-thick-top:before{content:'\e012'}.oi-arrow-top:before{content:'\e013'}.oi-audio-spectrum:before{content:'\e014'}.oi-audio:before{content:'\e015'}.oi-badge:before{content:'\e016'}.oi-ban:before{content:'\e017'}.oi-bar-chart:before{content:'\e018'}.oi-basket:before{content:'\e019'}.oi-battery-empty:before{content:'\e01a'}.oi-battery-full:before{content:'\e01b'}.oi-beaker:before{content:'\e01c'}.oi-bell:before{content:'\e01d'}.oi-bluetooth:before{content:'\e01e'}.oi-bold:before{content:'\e01f'}.oi-bolt:before{content:'\e020'}.oi-book:before{content:'\e021'}.oi-bookmark:before{content:'\e022'}.oi-box:before{content:'\e023'}.oi-briefcase:before{content:'\e024'}.oi-british-pound:before{content:'\e025'}.oi-browser:before{content:'\e026'}.oi-brush:before{content:'\e027'}.oi-bug:before{content:'\e028'}.oi-bullhorn:before{content:'\e029'}.oi-calculator:before{content:'\e02a'}.oi-calendar:before{content:'\e02b'}.oi-camera-slr:before{content:'\e02c'}.oi-caret-bottom:before{content:'\e02d'}.oi-caret-left:before{content:'\e02e'}.oi-caret-right:before{content:'\e02f'}.oi-caret-top:before{content:'\e030'}.oi-cart:before{content:'\e031'}.oi-chat:before{content:'\e032'}.oi-check:before{content:'\e033'}.oi-chevron-bottom:before{content:'\e034'}.oi-chevron-left:before{content:'\e035'}.oi-chevron-right:before{content:'\e036'}.oi-chevron-top:before{content:'\e037'}.oi-circle-check:before{content:'\e038'}.oi-circle-x:before{content:'\e039'}.oi-clipboard:before{content:'\e03a'}.oi-clock:before{content:'\e03b'}.oi-cloud-download:before{content:'\e03c'}.oi-cloud-upload:before{content:'\e03d'}.oi-cloud:before{content:'\e03e'}.oi-cloudy:before{content:'\e03f'}.oi-code:before{content:'\e040'}.oi-cog:before{content:'\e041'}.oi-collapse-down:before{content:'\e042'}.oi-collapse-left:before{content:'\e043'}.oi-collapse-right:before{content:'\e044'}.oi-collapse-up:before{content:'\e045'}.oi-command:before{content:'\e046'}.oi-comment-square:before{content:'\e047'}.oi-compass:before{content:'\e048'}.oi-contrast:before{content:'\e049'}.oi-copywriting:before{content:'\e04a'}.oi-credit-card:before{content:'\e04b'}.oi-crop:before{content:'\e04c'}.oi-dashboard:before{content:'\e04d'}.oi-data-transfer-download:before{content:'\e04e'}.oi-data-transfer-upload:before{content:'\e04f'}.oi-delete:before{content:'\e050'}.oi-dial:before{content:'\e051'}.oi-document:before{content:'\e052'}.oi-dollar:before{content:'\e053'}.oi-double-quote-sans-left:before{content:'\e054'}.oi-double-quote-sans-right:before{content:'\e055'}.oi-double-quote-serif-left:before{content:'\e056'}.oi-double-quote-serif-right:before{content:'\e057'}.oi-droplet:before{content:'\e058'}.oi-eject:before{content:'\e059'}.oi-elevator:before{content:'\e05a'}.oi-ellipses:before{content:'\e05b'}.oi-envelope-closed:before{content:'\e05c'}.oi-envelope-open:before{content:'\e05d'}.oi-euro:before{content:'\e05e'}.oi-excerpt:before{content:'\e05f'}.oi-expand-down:before{content:'\e060'}.oi-expand-left:before{content:'\e061'}.oi-expand-right:before{content:'\e062'}.oi-expand-up:before{content:'\e063'}.oi-external-link:before{content:'\e064'}.oi-eye:before{content:'\e065'}.oi-eyedropper:before{content:'\e066'}.oi-file:before{content:'\e067'}.oi-fire:before{content:'\e068'}.oi-flag:before{content:'\e069'}.oi-flash:before{content:'\e06a'}.oi-folder:before{content:'\e06b'}.oi-fork:before{content:'\e06c'}.oi-fullscreen-enter:before{content:'\e06d'}.oi-fullscreen-exit:before{content:'\e06e'}.oi-globe:before{content:'\e06f'}.oi-graph:before{content:'\e070'}.oi-grid-four-up:before{content:'\e071'}.oi-grid-three-up:before{content:'\e072'}.oi-grid-two-up:before{content:'\e073'}.oi-hard-drive:before{content:'\e074'}.oi-header:before{content:'\e075'}.oi-headphones:before{content:'\e076'}.oi-heart:before{content:'\e077'}.oi-home:before{content:'\e078'}.oi-image:before{content:'\e079'}.oi-inbox:before{content:'\e07a'}.oi-infinity:before{content:'\e07b'}.oi-info:before{content:'\e07c'}.oi-italic:before{content:'\e07d'}.oi-justify-center:before{content:'\e07e'}.oi-justify-left:before{content:'\e07f'}.oi-justify-right:before{content:'\e080'}.oi-key:before{content:'\e081'}.oi-laptop:before{content:'\e082'}.oi-layers:before{content:'\e083'}.oi-lightbulb:before{content:'\e084'}.oi-link-broken:before{content:'\e085'}.oi-link-intact:before{content:'\e086'}.oi-list-rich:before{content:'\e087'}.oi-list:before{content:'\e088'}.oi-location:before{content:'\e089'}.oi-lock-locked:before{content:'\e08a'}.oi-lock-unlocked:before{content:'\e08b'}.oi-loop-circular:before{content:'\e08c'}.oi-loop-square:before{content:'\e08d'}.oi-loop:before{content:'\e08e'}.oi-magnifying-glass:before{content:'\e08f'}.oi-map-marker:before{content:'\e090'}.oi-map:before{content:'\e091'}.oi-media-pause:before{content:'\e092'}.oi-media-play:before{content:'\e093'}.oi-media-record:before{content:'\e094'}.oi-media-skip-backward:before{content:'\e095'}.oi-media-skip-forward:before{content:'\e096'}.oi-media-step-backward:before{content:'\e097'}.oi-media-step-forward:before{content:'\e098'}.oi-media-stop:before{content:'\e099'}.oi-medical-cross:before{content:'\e09a'}.oi-menu:before{content:'\e09b'}.oi-microphone:before{content:'\e09c'}.oi-minus:before{content:'\e09d'}.oi-monitor:before{content:'\e09e'}.oi-moon:before{content:'\e09f'}.oi-move:before{content:'\e0a0'}.oi-musical-note:before{content:'\e0a1'}.oi-paperclip:before{content:'\e0a2'}.oi-pencil:before{content:'\e0a3'}.oi-people:before{content:'\e0a4'}.oi-person:before{content:'\e0a5'}.oi-phone:before{content:'\e0a6'}.oi-pie-chart:before{content:'\e0a7'}.oi-pin:before{content:'\e0a8'}.oi-play-circle:before{content:'\e0a9'}.oi-plus:before{content:'\e0aa'}.oi-power-standby:before{content:'\e0ab'}.oi-print:before{content:'\e0ac'}.oi-project:before{content:'\e0ad'}.oi-pulse:before{content:'\e0ae'}.oi-puzzle-piece:before{content:'\e0af'}.oi-question-mark:before{content:'\e0b0'}.oi-rain:before{content:'\e0b1'}.oi-random:before{content:'\e0b2'}.oi-reload:before{content:'\e0b3'}.oi-resize-both:before{content:'\e0b4'}.oi-resize-height:before{content:'\e0b5'}.oi-resize-width:before{content:'\e0b6'}.oi-rss-alt:before{content:'\e0b7'}.oi-rss:before{content:'\e0b8'}.oi-script:before{content:'\e0b9'}.oi-share-boxed:before{content:'\e0ba'}.oi-share:before{content:'\e0bb'}.oi-shield:before{content:'\e0bc'}.oi-signal:before{content:'\e0bd'}.oi-signpost:before{content:'\e0be'}.oi-sort-ascending:before{content:'\e0bf'}.oi-sort-descending:before{content:'\e0c0'}.oi-spreadsheet:before{content:'\e0c1'}.oi-star:before{content:'\e0c2'}.oi-sun:before{content:'\e0c3'}.oi-tablet:before{content:'\e0c4'}.oi-tag:before{content:'\e0c5'}.oi-tags:before{content:'\e0c6'}.oi-target:before{content:'\e0c7'}.oi-task:before{content:'\e0c8'}.oi-terminal:before{content:'\e0c9'}.oi-text:before{content:'\e0ca'}.oi-thumb-down:before{content:'\e0cb'}.oi-thumb-up:before{content:'\e0cc'}.oi-timer:before{content:'\e0cd'}.oi-transfer:before{content:'\e0ce'}.oi-trash:before{content:'\e0cf'}.oi-underline:before{content:'\e0d0'}.oi-vertical-align-bottom:before{content:'\e0d1'}.oi-vertical-align-center:before{content:'\e0d2'}.oi-vertical-align-top:before{content:'\e0d3'}.oi-video:before{content:'\e0d4'}.oi-volume-high:before{content:'\e0d5'}.oi-volume-low:before{content:'\e0d6'}.oi-volume-off:before{content:'\e0d7'}.oi-warning:before{content:'\e0d8'}.oi-wifi:before{content:'\e0d9'}.oi-wrench:before{content:'\e0da'}.oi-x:before{content:'\e0db'}.oi-yen:before{content:'\e0dc'}.oi-zoom-in:before{content:'\e0dd'}.oi-zoom-out:before{content:'\e0de'}
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Ftdi/FtdiUsbSerialPort.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Java.Lang;
4 | using Microsoft.Extensions.Logging;
5 | using Math = System.Math;
6 | // ReSharper disable InconsistentNaming
7 |
8 | namespace Maui.Serial.Platforms.Android.Drivers.Ftdi;
9 |
10 | public class FtdiUsbSerialPort : CommonUsbSerialPort
11 | {
12 | private const int USB_WRITE_TIMEOUT_MILLIS = 5000;
13 | private const int READ_HEADER_LENGTH = 2;
14 |
15 | private const int REQTYPE_HOST_TO_DEVICE = UsbConstants.UsbTypeVendor | 128;
16 |
17 | private const int RESET_REQUEST = 0;
18 | private const int MODEM_CONTROL_REQUEST = 1;
19 | private const int SET_BAUD_RATE_REQUEST = 3;
20 | private const int SET_DATA_REQUEST = 4;
21 | private const int GET_MODEM_STATUS_REQUEST = 5;
22 |
23 | private const int MODEM_CONTROL_DTR_ENABLE = 0x0101;
24 | private const int MODEM_CONTROL_DTR_DISABLE = 0x0100;
25 | private const int MODEM_CONTROL_RTS_ENABLE = 0x0202;
26 | private const int MODEM_CONTROL_RTS_DISABLE = 0x0200;
27 | private const int MODEM_STATUS_CTS = 0x10;
28 | private const int MODEM_STATUS_DSR = 0x20;
29 | private const int MODEM_STATUS_RI = 0x40;
30 | private const int MODEM_STATUS_CD = 0x80;
31 | private const int RESET_ALL = 0;
32 | private const int RESET_PURGE_RX = 1;
33 | private const int RESET_PURGE_TX = 2;
34 |
35 | private bool _dtr;
36 | private bool _rts;
37 |
38 |
39 | public FtdiUsbSerialPort(UsbManager manager, UsbDevice device, int portNumber, ILogger logger) : base(manager,
40 | device, portNumber, logger)
41 | {
42 | }
43 |
44 | [DebuggerStepThrough]
45 | public void Reset() => ExecuteCommand(RESET_REQUEST, RESET_ALL);
46 |
47 | [DebuggerStepThrough]
48 | public void Purge()
49 | {
50 | ExecuteCommand(RESET_REQUEST, RESET_PURGE_RX);
51 | ExecuteCommand(RESET_REQUEST, RESET_PURGE_TX);
52 | }
53 |
54 | protected override int CopyToReadBuffer(byte[] source, byte[] destination)
55 | {
56 | var maxPacketSize = ReadEndPoint.MaxPacketSize;
57 | var destPos = 0;
58 | var totalBytesRead = source.Length;
59 |
60 | for (var srcPos = 0; srcPos < totalBytesRead; srcPos += maxPacketSize)
61 | {
62 | var length = Math.Min(srcPos + maxPacketSize, totalBytesRead) - (srcPos + READ_HEADER_LENGTH);
63 | if (length < 0)
64 | {
65 | throw new IOException($"Expected at least {READ_HEADER_LENGTH} bytes");
66 | }
67 |
68 | Buffer.BlockCopy(source, srcPos + READ_HEADER_LENGTH, destination, destPos, length);
69 | destPos += length;
70 | }
71 |
72 | return destPos;
73 | }
74 |
75 | protected override void SetInterfaces(UsbDevice device)
76 | {
77 | var (usbInterface, index) = FindInterface(device, _ => true);
78 | SetReadEndPoint(usbInterface.GetEndpoint(0));
79 | SetWriteEndPoint(usbInterface.GetEndpoint(1));
80 | }
81 |
82 | protected override void SetParameters(
83 | UsbDeviceConnection connection,
84 | SerialPortParameters parameters)
85 | {
86 |
87 | SetBaudRate(parameters.BaudRate);
88 | var config = 0;
89 |
90 | config |= parameters.DataBits switch
91 | {
92 | DataBits.Bits5 => throw new UnsupportedOperationException($"Unsupported data bits: {parameters.DataBits}"),
93 | DataBits.Bits6 => throw new UnsupportedOperationException("Unsupported data bits: {parameters.DataBits}"),
94 | DataBits.Bits7 => DATABITS_7,
95 | DataBits.Bits8 => DATABITS_8,
96 | _ => throw new IllegalArgumentException($"Invalid data bits: {parameters.DataBits}")
97 | };
98 |
99 | switch (parameters.Partity)
100 | {
101 | case Parity.None:
102 | break;
103 | case Parity.Odd:
104 | config |= 0x100;
105 | break;
106 | case Parity.Even:
107 | config |= 0x200;
108 | break;
109 | case Parity.Mark:
110 | config |= 0x300;
111 | break;
112 | case Parity.Space:
113 | config |= 0x400;
114 | break;
115 | default:
116 | throw new IllegalArgumentException($"Unknown parity value: {parameters.BaudRate}");
117 | }
118 |
119 | switch (parameters.StopBits)
120 | {
121 | case StopBits.One:
122 | break;
123 | case StopBits.OnePointFive:
124 | throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
125 | case StopBits.Two:
126 | config |= 0x1000;
127 | break;
128 | case StopBits.NotSet:
129 | break;
130 | default:
131 | throw new IllegalArgumentException($"Unknown stopBits value: {parameters.StopBits}");
132 | }
133 |
134 | ExecuteCommand(SET_DATA_REQUEST, config);
135 |
136 | }
137 |
138 | public override bool GetCD() => (GetStatus() & MODEM_STATUS_CD) != 0;
139 |
140 | public override bool GetCTS() =>
141 | (GetStatus() & MODEM_STATUS_CTS) != 0;
142 |
143 | public override bool GetDSR() =>
144 | (GetStatus() & MODEM_STATUS_DSR) != 0;
145 |
146 | public override bool GetDTR() => _dtr;
147 |
148 | public override void SetDTR(bool value)
149 | {
150 | var result = UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST,
151 | value ? MODEM_CONTROL_DTR_ENABLE : MODEM_CONTROL_DTR_DISABLE, PortNumber + 1, null, 0,
152 | USB_WRITE_TIMEOUT_MILLIS);
153 | if (result != 0)
154 | {
155 | throw new IOException($"Set DTR failed: result={result}");
156 | }
157 |
158 | _dtr = value;
159 | }
160 |
161 | public override bool GetRI() =>
162 | (GetStatus() & MODEM_STATUS_RI) != 0;
163 |
164 | public override bool GetRTS() => _rts;
165 |
166 | public override void SetRTS(bool value)
167 | {
168 | var result = UsbConnection.ControlTransfer((UsbAddressing)REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST,
169 | value ? MODEM_CONTROL_RTS_ENABLE : MODEM_CONTROL_RTS_DISABLE, PortNumber + 1, null, 0,
170 | USB_WRITE_TIMEOUT_MILLIS);
171 | if (result != 0)
172 | {
173 | throw new IOException($"Set RTS failed: result={result}");
174 | }
175 |
176 | _rts = value;
177 | }
178 |
179 |
180 | private int GetStatus()
181 | {
182 | var data = new byte[2];
183 | ExecuteCommand(GET_MODEM_STATUS_REQUEST, 0, data, 2);
184 | return data[0];
185 | }
186 |
187 | private void ExecuteCommand(int command, int value, byte[] data = null, int expectedResult = 0, int portNumber = -1)
188 | {
189 | var result = ControlTransfer(
190 | (UsbAddressing)REQTYPE_HOST_TO_DEVICE,
191 | command,
192 | value,
193 | portNumber > 0 ? portNumber : PortNumber + 1,
194 | data,
195 | data?.Length ?? 0,
196 | USB_WRITE_TIMEOUT_MILLIS);
197 |
198 | if (result != expectedResult)
199 | {
200 | throw new IOException($"Command {command}/{value} failed: {result}");
201 | }
202 | }
203 |
204 | private void SetBaudRate(int baudRate)
205 | {
206 | if (baudRate <= 0)
207 | {
208 | throw new IllegalArgumentException($"Invalid baud rate: {baudRate}");
209 | }
210 |
211 | int divisor, subdivisor, effectiveBaudRate;
212 |
213 | switch (baudRate)
214 | {
215 | case > 3500000:
216 | throw new UnsupportedOperationException("Baud rate to high");
217 | case >= 2500000:
218 | divisor = 0;
219 | subdivisor = 0;
220 | effectiveBaudRate = 3000000;
221 | break;
222 | case >= 1750000:
223 | divisor = 1;
224 | subdivisor = 0;
225 | effectiveBaudRate = 2000000;
226 | break;
227 | default:
228 | divisor = (24000000 << 1) / baudRate;
229 | divisor = divisor + 1 >> 1; // round
230 | subdivisor = divisor & 0x07;
231 | divisor >>= 3;
232 | if (divisor > 0x3fff) // exceeds bit 13 at 183 baud
233 | throw new UnsupportedOperationException("Baud rate to low");
234 | effectiveBaudRate = (24000000 << 1) / ((divisor << 3) + subdivisor);
235 | effectiveBaudRate = effectiveBaudRate + 1 >> 1;
236 | break;
237 |
238 | }
239 |
240 | var baudRateError = Math.Abs(1.0 - effectiveBaudRate / (double)baudRate);
241 | if (baudRateError >= 0.031)
242 | {
243 | throw new UnsupportedOperationException(
244 | "Baud rate deviation %.1f%% is higher than allowed 3%%");
245 | }
246 |
247 | var value = divisor;
248 | var index = 0;
249 | switch (subdivisor)
250 | {
251 | case 0: break; // 16,15,14 = 000 - sub-integer divisor = 0
252 | case 4:
253 | value |= 0x4000;
254 | break; // 16,15,14 = 001 - sub-integer divisor = 0.5
255 | case 2:
256 | value |= 0x8000;
257 | break; // 16,15,14 = 010 - sub-integer divisor = 0.25
258 | case 1:
259 | value |= 0xc000;
260 | break; // 16,15,14 = 011 - sub-integer divisor = 0.125
261 | case 3:
262 | value |= 0x0000;
263 | index |= 1;
264 | break; // 16,15,14 = 100 - sub-integer divisor = 0.375
265 | case 5:
266 | value |= 0x4000;
267 | index |= 1;
268 | break; // 16,15,14 = 101 - sub-integer divisor = 0.625
269 | case 6:
270 | value |= 0x8000;
271 | index |= 1;
272 | break; // 16,15,14 = 110 - sub-integer divisor = 0.75
273 | case 7:
274 | value |= 0xc000;
275 | index |= 1;
276 | break; // 16,15,14 = 111 - sub-integer divisor = 0.875
277 | }
278 |
279 |
280 | ExecuteCommand(SET_BAUD_RATE_REQUEST, value, portNumber: index);
281 |
282 | }
283 | }
284 |
285 |
286 |
--------------------------------------------------------------------------------
/examples/SerialTerminal/Resources/Images/dotnet_bot.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
--------------------------------------------------------------------------------
/src/Maui.Serial/Platforms/Android/Drivers/Prolific/ProlificUsbSerialPortDriver.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Android.Hardware.Usb;
3 | using Java.Lang;
4 | using Maui.Serial.Platforms.Android.Usb;
5 | using Microsoft.Extensions.Logging;
6 | // ReSharper disable InconsistentNaming
7 |
8 | namespace Maui.Serial.Platforms.Android.Drivers.Prolific;
9 |
10 | [UsbDeviceDriver(UsbId.VENDOR_PROLIFIC,
11 | new[]
12 | {
13 | UsbId.PROLIFIC_PL2303, UsbId.PROLIFIC_PL2303GC, UsbId.PROLIFIC_PL2303GB, UsbId.PROLIFIC_PL2303GT,
14 | UsbId.PROLIFIC_PL2303GL, UsbId.PROLIFIC_PL2303GE, UsbId.PROLIFIC_PL2303GS
15 | })]
16 | public class ProlificUsbSerialPortDriver : CommonUsbSerialPort
17 | {
18 | private enum DeviceType
19 | {
20 | DEVICE_TYPE_01,
21 | DEVICE_TYPE_T,
22 | DEVICE_TYPE_HX,
23 | DEVICE_TYPE_HXN
24 | }
25 |
26 | private const int USB_READ_TIMEOUT_MILLIS = 1000;
27 | private const int USB_WRITE_TIMEOUT_MILLIS = 5000;
28 |
29 | private const int USB_RECIP_INTERFACE = 0x01;
30 |
31 | private const int VENDOR_READ_REQUEST = 0x01;
32 | private const int VENDOR_WRITE_REQUEST = 0x01;
33 | private const int VENDOR_READ_HXN_REQUEST = 0x81;
34 | private const int VENDOR_WRITE_HXN_REQUEST = 0x80;
35 |
36 | private const int VENDOR_OUT_REQTYPE = UsbSupport.UsbDirOut | UsbConstants.UsbTypeVendor;
37 | private const int VENDOR_IN_REQTYPE = UsbSupport.UsbDirIn | UsbConstants.UsbTypeVendor;
38 | private const int CTRL_OUT_REQTYPE = UsbSupport.UsbDirOut | UsbConstants.UsbTypeClass | USB_RECIP_INTERFACE;
39 |
40 | private const int WRITE_ENDPOINT = 0x02;
41 | private const int READ_ENDPOINT = 0x83;
42 | private const int INTERRUPT_ENDPOINT = 0x81;
43 |
44 | private const int RESET_HXN_REQUEST = 0x07;
45 | private const int FLUSH_RX_REQUEST = 0x08;
46 | private const int FLUSH_TX_REQUEST = 0x09;
47 |
48 | private const int SET_LINE_REQUEST = 0x20;
49 | private const int SET_CONTROL_REQUEST = 0x22;
50 | private const int GET_CONTROL_HXN_REQUEST = 0x80;
51 | private const int GET_CONTROL_REQUEST = 0x87;
52 |
53 | private const int RESET_HXN_RX_PIPE = 1;
54 | private const int RESET_HXN_TX_PIPE = 2;
55 |
56 | private const int CONTROL_DTR = 0x01;
57 | private const int CONTROL_RTS = 0x02;
58 |
59 | private const int GET_CONTROL_FLAG_CD = 0x02;
60 | private const int GET_CONTROL_FLAG_DSR = 0x04;
61 | private const int GET_CONTROL_FLAG_RI = 0x01;
62 | private const int GET_CONTROL_FLAG_CTS = 0x08;
63 |
64 | private const int GET_CONTROL_HXN_FLAG_CD = 0x40;
65 | private const int GET_CONTROL_HXN_FLAG_DSR = 0x20;
66 | private const int GET_CONTROL_HXN_FLAG_RI = 0x80;
67 | private const int GET_CONTROL_HXN_FLAG_CTS = 0x08;
68 |
69 | private const int STATUS_FLAG_CD = 0x01;
70 | private const int STATUS_FLAG_DSR = 0x02;
71 | private const int STATUS_FLAG_RI = 0x08;
72 | private const int STATUS_FLAG_CTS = 0x80;
73 |
74 | private const int STATUS_BUFFER_SIZE = 10;
75 | private const int STATUS_BYTE_IDX = 8;
76 |
77 | private DeviceType _deviceType = DeviceType.DEVICE_TYPE_HX;
78 | private UsbEndpoint _interruptEndpoint;
79 | private int _controlLinesValue;
80 |
81 | public ProlificUsbSerialPortDriver(UsbManager manager, UsbDevice device, int portNumber, ILogger logger)
82 | : base(manager, device, portNumber, logger)
83 | {
84 | }
85 |
86 |
87 | // ReSharper disable once CyclomaticComplexity
88 | protected override void SetInterfaces(UsbDevice device)
89 | {
90 | var usbInterface = GetInterfaceByIndex(device, 0);
91 |
92 |
93 | for (var i = 0; i < usbInterface.EndpointCount; ++i)
94 | {
95 | var currentEndpoint = usbInterface.GetEndpoint(i);
96 |
97 | switch (currentEndpoint?.Address)
98 | {
99 | case (UsbAddressing)READ_ENDPOINT:
100 | SetReadEndPoint(currentEndpoint);
101 | break;
102 |
103 | case (UsbAddressing)WRITE_ENDPOINT:
104 | SetWriteEndPoint(currentEndpoint);
105 | break;
106 |
107 | case (UsbAddressing)INTERRUPT_ENDPOINT:
108 | _interruptEndpoint = currentEndpoint;
109 | break;
110 | case UsbAddressing.In:
111 | break;
112 | case UsbAddressing.Out:
113 | break;
114 | case UsbAddressing.NumberMask:
115 | break;
116 | case UsbAddressing.XferInterrupt:
117 | break;
118 | case UsbAddressing.XferIsochronous:
119 | break;
120 | case null:
121 | break;
122 | default:
123 | throw new ArgumentOutOfRangeException(currentEndpoint?.Address.ToString());
124 | }
125 | }
126 |
127 | var rawDescriptors = UsbConnection.GetRawDescriptors();
128 | if (rawDescriptors == null || rawDescriptors.Length < 14)
129 | {
130 | throw new IOException("Could not get device descriptors");
131 | }
132 |
133 | var usbVersion = (rawDescriptors[3] << 8) + rawDescriptors[2];
134 | var deviceVersion = (rawDescriptors[13] << 8) + rawDescriptors[12];
135 | var maxPacketSize0 = rawDescriptors[7];
136 |
137 | if (UsbDevice.DeviceClass == UsbClass.Comm || maxPacketSize0 != 64)
138 | {
139 | _deviceType = DeviceType.DEVICE_TYPE_01;
140 | }
141 | else
142 | switch (deviceVersion)
143 | {
144 | case 0x300 when usbVersion == 0x200:
145 | case 0x500:
146 | _deviceType = DeviceType.DEVICE_TYPE_T;
147 | break;
148 | default:
149 | if (usbVersion == 0x200 && !TestHxStatus())
150 | {
151 | _deviceType = DeviceType.DEVICE_TYPE_HXN;
152 | }
153 | else
154 | {
155 | _deviceType = DeviceType.DEVICE_TYPE_HX;
156 | }
157 |
158 | break;
159 | }
160 |
161 | SetControlLines(_controlLinesValue);
162 | Reset();
163 | DoBlackMagic();
164 |
165 | }
166 |
167 | protected override void SetParameters(UsbDeviceConnection connection, SerialPortParameters parameters)
168 | {
169 | var baudRate = parameters.BaudRate;
170 | var lineRequestData = new byte[]
171 | {
172 | (byte)(baudRate & 0xff),
173 | (byte)((baudRate >> 8) & 0xff),
174 | (byte)((baudRate >> 16) & 0xff),
175 | (byte)((baudRate >> 24) & 0xff),
176 | parameters.StopBits switch
177 | {
178 | StopBits.NotSet => throw new IllegalArgumentException($"Unknown stopBits value: {parameters.StopBits}"),
179 | StopBits.One => 0,
180 | StopBits.OnePointFive => 1,
181 | StopBits.Two => 2,
182 | _ => throw new IllegalArgumentException($"Unknown stopBits value: {parameters.StopBits}")
183 | },
184 | parameters.Partity switch
185 | {
186 | Parity.None => 0,
187 | Parity.Odd => 1,
188 | Parity.Even => 2,
189 | Parity.Mark => 3,
190 | Parity.Space => 4,
191 | _ => throw new IllegalArgumentException($"Unknown parity value: {parameters.Partity}")
192 | },
193 | (byte)parameters.DataBits
194 | };
195 |
196 | CtrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);
197 | Reset();
198 | }
199 |
200 | public override bool GetCD() => TestStatusFlag(STATUS_FLAG_CD);
201 | public override bool GetCTS() => TestStatusFlag(STATUS_FLAG_CTS);
202 | public override bool GetDSR() => TestStatusFlag(STATUS_FLAG_DSR);
203 | public override bool GetDTR() => (_controlLinesValue & CONTROL_DTR) == CONTROL_DTR;
204 |
205 | public override void SetDTR(bool value)
206 | {
207 | int newControlLinesValue;
208 | if (value)
209 | {
210 | newControlLinesValue = _controlLinesValue | CONTROL_DTR;
211 | }
212 | else
213 | {
214 | newControlLinesValue = _controlLinesValue & ~CONTROL_DTR;
215 | }
216 |
217 | SetControlLines(newControlLinesValue);
218 | }
219 |
220 |
221 | public override bool GetRI() => TestStatusFlag(STATUS_FLAG_RI);
222 |
223 | public override bool GetRTS() => (_controlLinesValue & CONTROL_RTS) == CONTROL_RTS;
224 |
225 | public override void SetRTS(bool value)
226 | {
227 | int newControlLinesValue;
228 | if (value)
229 | {
230 | newControlLinesValue = _controlLinesValue | CONTROL_RTS;
231 | }
232 | else
233 | {
234 | newControlLinesValue = _controlLinesValue & ~CONTROL_RTS;
235 | }
236 |
237 | SetControlLines(newControlLinesValue);
238 | }
239 |
240 | private byte[] InControlTransfer(int requestType, int request,
241 | int value, int index, int length)
242 | {
243 | var buffer = new byte[length];
244 | var result = UsbConnection.ControlTransfer((UsbAddressing)requestType, request, value,
245 | index, buffer, length, USB_READ_TIMEOUT_MILLIS);
246 | if (result != length)
247 | {
248 | throw new IOException($"ControlTransfer with value {value} failed: {result}");
249 | }
250 |
251 | return buffer;
252 | }
253 |
254 | [DebuggerStepThrough]
255 | private void CtrlOut(int request, int value, int index, byte[] data) =>
256 | OutControlTransfer(CTRL_OUT_REQTYPE, request, value, index, data);
257 |
258 | private bool TestHxStatus()
259 | {
260 | try
261 | {
262 | InControlTransfer(VENDOR_IN_REQTYPE, VENDOR_READ_REQUEST, 0x8080, 0, 1);
263 | return true;
264 | }
265 | catch (IOException)
266 | {
267 | return false;
268 | }
269 | }
270 |
271 | private void DoBlackMagic()
272 | {
273 | if (_deviceType == DeviceType.DEVICE_TYPE_HXN)
274 | {
275 | return;
276 | }
277 |
278 | VendorIn(0x8484, 0, 1);
279 | VendorOut(0x0404, 0, null);
280 | VendorIn(0x8484, 0, 1);
281 | VendorIn(0x8383, 0, 1);
282 | VendorIn(0x8484, 0, 1);
283 | VendorOut(0x0404, 1, null);
284 | VendorIn(0x8484, 0, 1);
285 | VendorIn(0x8383, 0, 1);
286 | VendorOut(0, 1, null);
287 | VendorOut(1, 0, null);
288 | VendorOut(2, (_deviceType == DeviceType.DEVICE_TYPE_HX) ? 0x44 : 0x24, null);
289 | }
290 |
291 | private void SetControlLines(int newControlLinesValue)
292 | {
293 | CtrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null);
294 | _controlLinesValue = newControlLinesValue;
295 | }
296 |
297 | private int GetStatus()
298 | {
299 | var buffer = new byte[STATUS_BUFFER_SIZE];
300 | var readBytesCount = UsbConnection.BulkTransfer(_interruptEndpoint, buffer, STATUS_BUFFER_SIZE, 500);
301 | var status = 0;
302 |
303 | switch (readBytesCount)
304 | {
305 | case <= 0:
306 | break;
307 | case STATUS_BUFFER_SIZE:
308 | status = buffer[STATUS_BYTE_IDX] & 0xff;
309 | break;
310 | default:
311 | throw new IOException(
312 | $"Invalid CTS / DSR / CD / RI status buffer received, expected {STATUS_BUFFER_SIZE} bytes, but received {readBytesCount}");
313 | }
314 |
315 | if (_deviceType == DeviceType.DEVICE_TYPE_HXN)
316 | {
317 | var data = VendorIn(GET_CONTROL_HXN_REQUEST, 0, 1);
318 | if ((data[0] & GET_CONTROL_HXN_FLAG_CTS) == 0) status |= STATUS_FLAG_CTS;
319 | if ((data[0] & GET_CONTROL_HXN_FLAG_DSR) == 0) status |= STATUS_FLAG_DSR;
320 | if ((data[0] & GET_CONTROL_HXN_FLAG_CD) == 0) status |= STATUS_FLAG_CD;
321 | if ((data[0] & GET_CONTROL_HXN_FLAG_RI) == 0) status |= STATUS_FLAG_RI;
322 | }
323 | else
324 | {
325 | var data = VendorIn(GET_CONTROL_REQUEST, 0, 1);
326 | if ((data[0] & GET_CONTROL_FLAG_CTS) == 0) status |= STATUS_FLAG_CTS;
327 | if ((data[0] & GET_CONTROL_FLAG_DSR) == 0) status |= STATUS_FLAG_DSR;
328 | if ((data[0] & GET_CONTROL_FLAG_CD) == 0) status |= STATUS_FLAG_CD;
329 | if ((data[0] & GET_CONTROL_FLAG_RI) == 0) status |= STATUS_FLAG_RI;
330 | }
331 |
332 | return status;
333 | }
334 |
335 | private void Reset()
336 | {
337 | if (_deviceType == DeviceType.DEVICE_TYPE_HXN)
338 | {
339 | const int index = RESET_HXN_RX_PIPE | RESET_HXN_TX_PIPE;
340 | VendorOut(RESET_HXN_REQUEST, index, null);
341 | }
342 | else
343 | {
344 |
345 | VendorOut(FLUSH_RX_REQUEST, 0, null);
346 | VendorOut(FLUSH_TX_REQUEST, 0, null);
347 | }
348 | }
349 |
350 | private void OutControlTransfer(int requestType, int request,
351 | int value, int index, byte[] data)
352 | {
353 | var length = data?.Length ?? 0;
354 | var result = UsbConnection.ControlTransfer((UsbAddressing)requestType, request, value,
355 | index, data, length, USB_WRITE_TIMEOUT_MILLIS);
356 | if (result != length)
357 | {
358 | throw new IOException($"ControlTransfer with value {value} failed: {result}");
359 | }
360 | }
361 |
362 | [DebuggerStepThrough]
363 | private byte[] VendorIn(int value, int index, int length)
364 | {
365 | var request = (_deviceType == DeviceType.DEVICE_TYPE_HXN) ? VENDOR_READ_HXN_REQUEST : VENDOR_READ_REQUEST;
366 | return InControlTransfer(VENDOR_IN_REQTYPE, request, value, index, length);
367 | }
368 |
369 | [DebuggerStepThrough]
370 | private void VendorOut(int value, int index, byte[] data)
371 | {
372 | var request = (_deviceType == DeviceType.DEVICE_TYPE_HXN) ? VENDOR_WRITE_HXN_REQUEST : VENDOR_WRITE_REQUEST;
373 | OutControlTransfer(VENDOR_OUT_REQTYPE, request, value, index, data);
374 | }
375 |
376 | [DebuggerStepThrough]
377 | private bool TestStatusFlag(int flag) => (GetStatus() & flag) == flag;
378 | }
--------------------------------------------------------------------------------