diff --git a/App.axaml b/App.axaml new file mode 100644 index 0000000..054d670 --- /dev/null +++ b/App.axaml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/App.axaml.cs b/App.axaml.cs new file mode 100644 index 0000000..35c325d --- /dev/null +++ b/App.axaml.cs @@ -0,0 +1,47 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Data.Core; +using Avalonia.Data.Core.Plugins; +using System.Linq; +using Avalonia.Markup.Xaml; +using OMControl.ViewModels; +using OMControl.Views; + +namespace OMControl; + +public partial class App : Application +{ + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + // Avoid duplicate validations from both Avalonia and the CommunityToolkit. + // More info: https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins + DisableAvaloniaDataAnnotationValidation(); + desktop.MainWindow = new MainWindow + { + DataContext = new MainWindowViewModel(), + }; + } + + base.OnFrameworkInitializationCompleted(); + } + + private void DisableAvaloniaDataAnnotationValidation() + { + // Get an array of plugins to remove + var dataValidationPluginsToRemove = + BindingPlugins.DataValidators.OfType().ToArray(); + + // remove each entry found + foreach (var plugin in dataValidationPluginsToRemove) + { + BindingPlugins.DataValidators.Remove(plugin); + } + } +} \ No newline at end of file diff --git a/Assets/avalonia-logo.ico b/Assets/avalonia-logo.ico new file mode 100644 index 0000000..f7da8bb Binary files /dev/null and b/Assets/avalonia-logo.ico differ diff --git a/OMControl.csproj b/OMControl.csproj new file mode 100644 index 0000000..0d7bf26 --- /dev/null +++ b/OMControl.csproj @@ -0,0 +1,28 @@ + + + WinExe + net9.0 + enable + app.manifest + true + + + + + + + + + + + + + + + None + All + + + + + diff --git a/OMControl.sln b/OMControl.sln new file mode 100644 index 0000000..d960ed7 --- /dev/null +++ b/OMControl.sln @@ -0,0 +1,24 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.2.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OMControl", "OMControl.csproj", "{354B5A1B-F5A0-FE1B-2381-A190E018DE95}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {354B5A1B-F5A0-FE1B-2381-A190E018DE95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {354B5A1B-F5A0-FE1B-2381-A190E018DE95}.Debug|Any CPU.Build.0 = Debug|Any CPU + {354B5A1B-F5A0-FE1B-2381-A190E018DE95}.Release|Any CPU.ActiveCfg = Release|Any CPU + {354B5A1B-F5A0-FE1B-2381-A190E018DE95}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7AE9FAE1-5E72-4A75-BDB8-0761F1E7B61E} + EndGlobalSection +EndGlobal diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..1197fa9 --- /dev/null +++ b/Program.cs @@ -0,0 +1,21 @@ +using Avalonia; +using System; + +namespace OMControl; + +sealed class Program +{ + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) => BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace(); +} diff --git a/Services/SerialPortService.cs b/Services/SerialPortService.cs new file mode 100644 index 0000000..f138556 --- /dev/null +++ b/Services/SerialPortService.cs @@ -0,0 +1,53 @@ +using System; +using System.IO.Ports; + +namespace OMControl.Services; + +public class SerialPortService : IDisposable +{ + private SerialPort? _serialPort; + public bool IsOpen => _serialPort?.IsOpen == true; + public event Action? DataReceived; + + public void Open(string portName, int baudRate = 9600) + { + if (IsOpen) return; + + _serialPort = new SerialPort(portName, baudRate) + { + NewLine = "\n", + ReadTimeout = 1000, + WriteTimeout = 1000 + }; + + _serialPort.DataReceived += OnDataReceived; + _serialPort.Open(); + } + + public void Close() + { + if (_serialPort == null) return; + _serialPort.DataReceived -= OnDataReceived; + _serialPort.Close(); + _serialPort.Dispose(); + _serialPort = null; + } + + public void Send(string data) + { + if (!IsOpen || _serialPort == null) return; + _serialPort.WriteLine(data); + } + + private void OnDataReceived(object sender, SerialDataReceivedEventArgs e) + { + try + { + var data = _serialPort?.ReadLine(); + if (data != null) DataReceived?.Invoke(data); + } + catch { } + } + + public void Dispose() => Close(); +} diff --git a/ViewLocator.cs b/ViewLocator.cs new file mode 100644 index 0000000..bffde9b --- /dev/null +++ b/ViewLocator.cs @@ -0,0 +1,37 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using OMControl.ViewModels; + +namespace OMControl; + +/// +/// Given a view model, returns the corresponding view if possible. +/// +[RequiresUnreferencedCode( + "Default implementation of ViewLocator involves reflection which may be trimmed away.", + Url = "https://docs.avaloniaui.net/docs/concepts/view-locator")] +public class ViewLocator : IDataTemplate +{ + public Control? Build(object? param) + { + if (param is null) + return null; + + var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); + var type = Type.GetType(name); + + if (type != null) + { + return (Control)Activator.CreateInstance(type)!; + } + + return new TextBlock { Text = "Not Found: " + name }; + } + + public bool Match(object? data) + { + return data is ViewModelBase; + } +} diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..b89f6cb --- /dev/null +++ b/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.IO.Ports; +using System.Runtime.CompilerServices; +using System.Windows.Input; +using Avalonia.Threading; +using OMControl.Services; + +namespace OMControl.ViewModels; + +public class MainWindowViewModel : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + void Raise([CallerMemberName] string? p = null) => PropertyChanged?.Invoke(this, new(p)); + + private readonly SerialPortService _serial = new(); + + public ObservableCollection AvailablePorts { get; } = new(); + + private string? _selectedPort; + public string? SelectedPort { get => _selectedPort; set { _selectedPort = value; Raise(); } } + + private string _receivedData = ""; + public string ReceivedData { get => _receivedData; set { _receivedData = value; Raise(); } } + + private string _sendData = ""; + public string SendData { get => _sendData; set { _sendData = value; Raise(); } } + + string _field01 = ""; public string Field01 { get => _field01; set { _field01 = value; Raise(); } } + string _field02 = ""; public string Field02 { get => _field02; set { _field02 = value; Raise(); } } + string _field03 = ""; public string Field03 { get => _field03; set { _field03 = value; Raise(); } } + + public ICommand RefreshPortsCommand { get; } + public ICommand ConnectCommand { get; } + public ICommand DisconnectCommand { get; } + public ICommand SendCommand { get; } + public ICommand ClearCommand { get; } + + public MainWindowViewModel() + { + RefreshPortsCommand = new RelayCommand(RefreshPorts); + ConnectCommand = new RelayCommand(Connect); + DisconnectCommand = new RelayCommand(Disconnect); + SendCommand = new RelayCommand(Send); + ClearCommand = new RelayCommand(ClearAll); + + _serial.DataReceived += data => + { + Dispatcher.UIThread.Post(() => ReceivedData += data + Environment.NewLine); + }; + + RefreshPorts(); + } + + private void RefreshPorts() + { + AvailablePorts.Clear(); + foreach (var p in SerialPort.GetPortNames()) + AvailablePorts.Add(p); + + if (SelectedPort == null && AvailablePorts.Count > 0) + SelectedPort = AvailablePorts[0]; + } + + private void Connect() + { + if (SelectedPort is null) return; + _serial.Open(SelectedPort, 9600); + } + + private void Disconnect() => _serial.Close(); + + private void Send() + { + if (!string.IsNullOrWhiteSpace(SendData)) + _serial.Send(SendData); + } + + private void ClearAll() + { + Field01 = Field02 = Field03 = ""; + ReceivedData = ""; + SendData = ""; + } +} + +public sealed class RelayCommand : ICommand +{ + private readonly Action _execute; + private readonly Func? _canExecute; + + public RelayCommand(Action execute, Func? canExecute = null) + { + _execute = execute; + _canExecute = canExecute; + } + + public event EventHandler? CanExecuteChanged; + public bool CanExecute(object? parameter) => _canExecute?.Invoke() ?? true; + public void Execute(object? parameter) => _execute(); +} diff --git a/ViewModels/ViewModelBase.cs b/ViewModels/ViewModelBase.cs new file mode 100644 index 0000000..53d068c --- /dev/null +++ b/ViewModels/ViewModelBase.cs @@ -0,0 +1,7 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace OMControl.ViewModels; + +public abstract class ViewModelBase : ObservableObject +{ +} diff --git a/Views/MainWindow.axaml b/Views/MainWindow.axaml new file mode 100644 index 0000000..ce90bee --- /dev/null +++ b/Views/MainWindow.axaml @@ -0,0 +1,59 @@ + + + + + + + + + + +