Fix multiple poller situational problems

This commit is contained in:
Felix Weiß
2023-07-27 19:03:02 +02:00
parent 1f33ebb8d3
commit 38b83affd7
32 changed files with 1243 additions and 130 deletions

9
Examples.WPF/App.xaml Normal file
View File

@@ -0,0 +1,9 @@
<Application x:Class="Examples.WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Examples.WPF"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

85
Examples.WPF/App.xaml.cs Normal file
View File

@@ -0,0 +1,85 @@
using Examples.WPF.ViewModels;
using MewtocolNet;
using MewtocolNet.Logging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Navigation;
namespace Examples.WPF;
public partial class App : Application {
public static AppViewModel ViewModel { get; private set; } = null!;
public static new App Current = null!;
public static new MainWindow MainWindow = null!;
public static ObservableCollection<TextBlock> LoggerItems = null!;
internal static event Action? LogEventProcessed;
protected override void OnStartup(StartupEventArgs e) {
ViewModel = new AppViewModel();
Current = this;
LoggerItems = new();
Logger.LogLevel = LogLevel.Verbose;
Logger.DefaultTargets = LoggerTargets.Trace;
Logger.OnNewLogMessage((d, l, m) => {
Application.Current.Dispatcher.BeginInvoke(() => {
Brush msgColor = null!;
switch (l) {
case LogLevel.Error:
msgColor = Brushes.Red;
break;
case LogLevel.Change:
msgColor = Brushes.Blue;
break;
case LogLevel.Verbose:
msgColor = Brushes.Gold;
break;
case LogLevel.Critical:
msgColor = Brushes.Gray;
break;
}
if (LoggerItems.Count > 1000) LoggerItems.RemoveAt(0);
var contRun = msgColor == null ? new Run(m) : new Run(m) {
Foreground = msgColor,
};
LoggerItems.Add(new TextBlock {
Inlines = {
new Run($"[{d:hh:mm:ss:ff}] ") {
Foreground = Brushes.LimeGreen,
},
contRun
}
});
LogEventProcessed?.Invoke();
}, System.Windows.Threading.DispatcherPriority.Background);
});
}
}

View File

@@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\MewtocolNet\MewtocolNet.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,162 @@
<Window x:Class="Examples.WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Examples.WPF"
d:DataContext="{d:DesignInstance local:MainWindow, IsDesignTimeCreatable=True}"
mc:Ignorable="d"
MinWidth="500"
MinHeight="400"
Height="600"
Width="800"
Title="MewtocolNet WPF Demo">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
<RowDefinition MinHeight="30" Height="150"/>
</Grid.RowDefinitions>
<ContentControl x:Name="mainContent"/>
<GridSplitter Grid.Row="1"
HorizontalAlignment="Stretch"
Background="Gray"
ShowsPreview="true"
Height="5">
<GridSplitter.Template>
<ControlTemplate>
<Separator/>
</ControlTemplate>
</GridSplitter.Template>
</GridSplitter>
<Grid Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Border Background="LightGray"/>
<StackPanel HorizontalAlignment="Left"
Orientation="Horizontal">
<TextBlock Text="Logger"
Margin="5"/>
<Border Width="1"
Margin="5"
Background="Gray"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Rx"
Margin="5"/>
<Ellipse IsEnabled="{Binding AppViewModel.Plc.IsReceiving, Mode=OneWay}"
Fill="Lime"
Width="10"
Height="10">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value=".1"/>
</Trigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
<TextBlock Text="Tx"
Margin="5"/>
<Ellipse Fill="Orange"
IsEnabled="{Binding AppViewModel.Plc.IsSending, Mode=OneWay}"
Width="10"
Height="10">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value=".1"/>
</Trigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
<Border Width="1"
Margin="5"
Background="Gray"/>
<TextBlock Text="{Binding AppViewModel.Plc.BytesPerSecondDownstream, Mode=OneWay}"
VerticalAlignment="Center"/>
<Border Width="1"
Margin="5"
Background="Gray"/>
<TextBlock Text="{Binding AppViewModel.Plc.BytesPerSecondUpstream, Mode=OneWay}"
VerticalAlignment="Center"/>
<StackPanel.Style>
<Style TargetType="StackPanel">
<Style.Triggers>
<DataTrigger Binding="{Binding AppViewModel.PlcIsNull}" Value="True">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
</StackPanel>
</StackPanel>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Right">
<Button Content="Expand"
Margin="2"/>
<ToggleButton Content="Autoscroll"
IsChecked="True"
Margin="2"
x:Name="autoScrollBtn"/>
</StackPanel>
<ListBox Grid.Row="1"
Background="Black"
Foreground="White"
BorderThickness="0"
VirtualizingPanel.IsVirtualizing="true"
VirtualizingPanel.VirtualizationMode="Recycling"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
ItemsSource="{Binding LoggerItems, Mode=OneWay}"
x:Name="loggerList">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
<Border Background="Black"
Grid.Row="2">
<TextBlock Text=">"
Foreground="White"
Margin="5,0,0,0"/>
</Border>
</Grid>
</Grid>
</Window>

View File

@@ -0,0 +1,57 @@
using Examples.WPF.ViewModels;
using Examples.WPF.Views;
using MewtocolNet;
using MewtocolNet.Logging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Examples.WPF;
public partial class MainWindow : Window {
public ObservableCollection<TextBlock> LoggerItems => App.LoggerItems;
public AppViewModel AppViewModel => App.ViewModel;
public MainWindow() {
InitializeComponent();
this.DataContext = this;
App.MainWindow = this;
mainContent.Content = new ConnectView();
loggerList.PreviewMouseWheel += (s, e) => {
autoScrollBtn.IsChecked = false;
};
App.LogEventProcessed += () => {
Application.Current.Dispatcher.BeginInvoke(() => {
if (autoScrollBtn?.IsChecked != null && autoScrollBtn.IsChecked.Value)
loggerList.ScrollIntoView(App.LoggerItems.Last());
}, System.Windows.Threading.DispatcherPriority.Send);
};
}
}

View File

@@ -0,0 +1,30 @@
using MewtocolNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examples.WPF.ViewModels {
public class AppViewModel : ViewModelBase {
private IPlc? plc;
public bool PlcIsNull => plc == null;
public bool PlcIsNotNull => plc != null;
public IPlc? Plc {
get => plc;
set {
plc = value;
OnPropChange();
OnPropChange(nameof(PlcIsNull));
OnPropChange(nameof(PlcIsNotNull));
}
}
}
}

View File

@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Configuration.Internal;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using MewtocolNet;
using MewtocolNet.ComCassette;
namespace Examples.WPF.ViewModels;
internal class ConnectViewViewModel : ViewModelBase {
private bool hasComports = false;
private IEnumerable<int> baudRates = null!;
private IEnumerable<string> comPorts = null!;
private IEnumerable<CassetteInformation> foundCassettes = null!;
private string selectedIP = "192.168.115.210";
private string selectedPort = "9094";
private bool isConnecting;
public IEnumerable<int> BaudRates {
get => baudRates;
set {
baudRates = value;
OnPropChange();
}
}
public IEnumerable<string> ComPorts {
get => comPorts;
set {
comPorts = value;
OnPropChange();
}
}
public IEnumerable<CassetteInformation> FoundCassettes {
get => foundCassettes;
set {
foundCassettes = value;
OnPropChange();
}
}
public bool HasComports {
get => hasComports;
set {
hasComports = value;
OnPropChange();
}
}
public string SelectedIP {
get { return selectedIP; }
set {
selectedIP = value;
OnPropChange();
}
}
public string SelectedPort {
get { return selectedPort; }
set {
selectedPort = value;
OnPropChange();
}
}
public bool IsConnecting {
get { return isConnecting; }
set {
isConnecting = value;
OnPropChange();
}
}
private DispatcherTimer tm;
public ConnectViewViewModel() {
BaudRates = Mewtocol.GetUseableBaudRates();
ScanTimerTick(null, null!);
tm = new DispatcherTimer {
Interval = TimeSpan.FromSeconds(3),
};
tm.Tick += ScanTimerTick;
tm.Start();
}
private async void ScanTimerTick(object? sender, EventArgs e) {
ComPorts = Mewtocol.GetSerialPortNames();
HasComports = ComPorts != null && ComPorts.Count() > 0;
var found = await CassetteFinder.FindClientsAsync(timeoutMs: 1000);
if (FoundCassettes == null || !Enumerable.SequenceEqual(found, FoundCassettes))
FoundCassettes = found;
}
internal void SelectedCassette (CassetteInformation cassette) {
SelectedIP = cassette.IPAddress.ToString();
SelectedPort = cassette.Port.ToString();
}
internal void EndTimer() => tm.Stop();
}

View File

@@ -0,0 +1,14 @@
using MewtocolNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examples.WPF.ViewModels;
public class PlcDataViewViewModel : ViewModelBase {
public IPlc Plc => App.ViewModel.Plc!;
}

View File

@@ -0,0 +1,18 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Examples.WPF.ViewModels;
public abstract class ViewModelBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler? PropertyChanged;
public void PropChange(string _name) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(_name));
}
protected void OnPropChange([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

View File

@@ -0,0 +1,129 @@
<UserControl x:Class="Examples.WPF.Views.ConnectView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Examples.WPF.Views"
xmlns:vm="clr-namespace:Examples.WPF.ViewModels"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance vm:ConnectViewViewModel, IsDesignTimeCreatable=True}"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Margin="10">
<StackPanel>
<StackPanel.Resources>
<Style TargetType="TextBox">
<Setter Property="Padding" Value="5"/>
</Style>
</StackPanel.Resources>
<StackPanel>
<TextBlock Text="Connect to a PLC"
FontSize="24"/>
<Label Content="Set your connection type"/>
<ComboBox SelectedIndex="0" x:Name="conTypeCombo">
<ComboBoxItem>Ethernet</ComboBoxItem>
<ComboBoxItem IsEnabled="{Binding HasComports}">Serial</ComboBoxItem>
</ComboBox>
</StackPanel>
<Separator/>
<StackPanel MinWidth="200">
<TextBlock Text="Cassettes"/>
<DataGrid ItemsSource="{Binding FoundCassettes}"
SelectionChanged="SelectedCassette"
AutoGenerateColumns="False"
MinHeight="150"
MaxHeight="200"
IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width=".5*"/>
<DataGridTextColumn Header="IP" Binding="{Binding IPAddress}" Width=".3*"/>
<DataGridTextColumn Header="Port" Binding="{Binding Port}" Width=".3*"/>
<DataGridCheckBoxColumn Header="DHCP" Binding="{Binding UsesDHCP}" Width="auto"/>
<DataGridTextColumn Header="MAC" Binding="{Binding MacAddressStr, Mode=OneWay}" Width="auto"/>
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="auto"/>
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding Port}" Value="0">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
<TextBlock Text="Connection"/>
<StackPanel Orientation="Horizontal">
<Label Content="IP Address"
VerticalAlignment="Center"/>
<TextBox Text="{Binding SelectedIP}"
VerticalAlignment="Center"/>
<Label Content="Port"
VerticalAlignment="Center"/>
<TextBox Text="{Binding SelectedPort}"
VerticalAlignment="Center"/>
<Button Content="Connect"
Click="ClickedConnectEth"
VerticalAlignment="Center"
Padding="5"
Margin="10,0,0,0">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding IsConnecting}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
<StackPanel.Style>
<Style TargetType="StackPanel">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedIndex, ElementName=conTypeCombo}" Value="0">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
</StackPanel>
<StackPanel MinWidth="200"
HorizontalAlignment="Left">
<StackPanel Orientation="Vertical">
<Label Content="COM Port"/>
<ComboBox ItemsSource="{Binding ComPorts}"
SelectedIndex="0"/>
<Label Content="BaudRate"/>
<ComboBox ItemsSource="{Binding BaudRates}"
SelectedIndex="0"/>
</StackPanel>
<StackPanel.Style>
<Style TargetType="StackPanel">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedIndex, ElementName=conTypeCombo}" Value="1">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,78 @@
using Examples.WPF.ViewModels;
using MewtocolNet;
using MewtocolNet.ComCassette;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Examples.WPF.Views;
/// <summary>
/// Interaktionslogik für ConnectView.xaml
/// </summary>
public partial class ConnectView : UserControl {
private ConnectViewViewModel viewModel;
public ConnectView() {
InitializeComponent();
viewModel = new ConnectViewViewModel();
this.DataContext = viewModel;
Unloaded += (s, e) => viewModel.EndTimer();
}
private void SelectedCassette(object sender, SelectionChangedEventArgs e) {
var cassette = (CassetteInformation)((DataGrid)sender).SelectedItem;
if (cassette == null) return;
viewModel.SelectedCassette(cassette);
}
private void ClickedConnectEth(object sender, RoutedEventArgs e) {
Application.Current.Dispatcher.BeginInvoke(async () => {
viewModel.IsConnecting = true;
var parsedInt = int.Parse(viewModel.SelectedPort);
App.ViewModel.Plc = Mewtocol.Ethernet(viewModel.SelectedIP, parsedInt)
.WithPoller()
.WithRegisters(b => {
b.Struct<short>("DT0").Build();
b.Struct<short>("DT0").AsArray(30).Build();
})
.Build();
await App.ViewModel.Plc.ConnectAsync();
if (App.ViewModel.Plc.IsConnected) {
App.MainWindow.mainContent.Content = new PlcDataView();
}
viewModel.IsConnecting = false;
}, System.Windows.Threading.DispatcherPriority.Send);
}
}

View File

@@ -0,0 +1,76 @@
<UserControl x:Class="Examples.WPF.Views.PlcDataView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:Examples.WPF.ViewModels"
xmlns:local="clr-namespace:Examples.WPF.Views"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance vm:PlcDataViewViewModel, IsDesignTimeCreatable=True}"
d:DesignHeight="450"
d:DesignWidth="800">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel>
<TextBlock>
<Run Text="{Binding Plc.PlcInfo.TypeName, Mode=OneWay}"
FontSize="24"
FontWeight="SemiBold"/>
<Run Text="{Binding Plc.PlcInfo.CpuVersion, StringFormat='v{0}', Mode=OneWay}"
FontSize="24"
FontWeight="Light"/>
</TextBlock>
<TextBlock Text="{Binding Plc.PlcInfo.TypeCode, StringFormat='#{0:X}', Mode=OneWay}"
FontSize="18"/>
<ItemsControl ItemsSource="{Binding Plc.PlcInfo.OperationModeTags, Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="LightGray"
CornerRadius="5"
Margin="2"
Padding="5">
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Plc.PlcInfo.HardwareInformationTags, Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="LightGray"
CornerRadius="5"
Margin="2"
Padding="5">
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,32 @@
using Examples.WPF.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Examples.WPF.Views;
public partial class PlcDataView : UserControl {
private PlcDataViewViewModel viewModel;
public PlcDataView() {
InitializeComponent();
viewModel = new PlcDataViewViewModel();
this.DataContext = viewModel;
}
}