首次提交:添加src文件夹代码

This commit is contained in:
2026-01-26 22:50:44 +08:00
commit f4529404b1
3626 changed files with 3403529 additions and 0 deletions

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.32413.511
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StandardDomeNewApp", "StandardDomeNewApp\StandardDomeNewApp.csproj", "{0A296577-286A-4DC4-A39B-B194A2C80C0F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0A296577-286A-4DC4-A39B-B194A2C80C0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A296577-286A-4DC4-A39B-B194A2C80C0F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A296577-286A-4DC4-A39B-B194A2C80C0F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A296577-286A-4DC4-A39B-B194A2C80C0F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4A1AD835-02DB-47A0-B779-D640C5921CEC}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,463 @@
<prism:PrismApplication x:Class="StandardDomeNewApp.App"
xmlns:prism="http://prismlibrary.com/"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StandardDomeNewApp"
xmlns:controls="clr-namespace:StandardDomeNewApp.Modules"
>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--HandyControl-->
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
<!--Fluent-->
<ResourceDictionary Source="pack://application:,,,/Fluent;component/Themes/Generic.xaml" />
<ResourceDictionary Source="pack://application:,,,/Fluent;component/Themes/Themes/Light.Green.xaml" />
<!--<ResourceDictionary Source="pack://application:,,,/Fluent;component/Themes/Themes/Dark.Green.xaml" />-->
<!--AvalonDock-->
<ResourceDictionary Source="pack://application:,,,/AvalonDock;component/Themes/Generic.xaml" />
<ResourceDictionary Source="pack://application:,,,/AvalonDock.Themes.VS2013;component/LightBrushs.xaml" />
<!--<ResourceDictionary Source="pack://application:,,,/AvalonDock.Themes.VS2013;component/DarkBrushs.xaml" />-->
<ResourceDictionary Source="Language\en-US.xaml" />
<ResourceDictionary Source="Language\zh-CN.xaml" />
<ResourceDictionary Source="/StandardDomeNewApp;component/Modules/ComboBoxDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
<HierarchicalDataTemplate x:Key="ItemNode" ItemsSource="{Binding menuInfoModels,Mode=TwoWay}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button BorderThickness="0" Background="Transparent" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="-10,0,0,0" ToolTip="{Binding textValue,Mode=TwoWay}">
<Image Source="{Binding picPath,Mode=TwoWay}"/>
</Button>
<TextBlock Text="{Binding textValue,Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Left"
Foreground="{Binding foreGround,Mode=TwoWay}" FontSize="{Binding fontSize,Mode=TwoWay}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
<!--ToggleButton默认的样式-->
<Style x:Key="DefaultToggleSwitch" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<ControlTemplate.Resources>
<Storyboard x:Key="OnChecked">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.TargetName="path">
<EasingThicknessKeyFrame KeyTime="0" Value="40,0,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="OnUnchecked">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.TargetName="path">
<EasingThicknessKeyFrame KeyTime="0" Value="0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Border x:Name="toggleBorder"
CornerRadius="13"
Background="Green"
Width="60"
Height="26"
BorderThickness="1"
BorderBrush="Gray">
<Grid>
<Path x:Name="path">
<Path.Fill>
<LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
<GradientStop Color="White"/>
</LinearGradientBrush>
</Path.Fill>
<Path.Data>
<GeometryGroup>
<GeometryGroup.Children>
<EllipseGeometry Center="6,12" RadiusX="9" RadiusY="9"/>
</GeometryGroup.Children>
</GeometryGroup>
</Path.Data>
</Path>
</Grid>
</Border>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="ToggleButton.Checked">
<BeginStoryboard Storyboard="{StaticResource OnChecked}"/>
</EventTrigger>
<EventTrigger RoutedEvent="ToggleButton.Unchecked">
<BeginStoryboard Storyboard="{StaticResource OnUnchecked}"/>
</EventTrigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="DimGray"/>
<Setter TargetName="toggleBorder" Property="Background" Value="Green"/>
<Setter TargetName="toggleBorder" Property="BorderBrush" Value="Green"/>
</Trigger>
<Trigger Property="IsChecked" Value="False">
<Setter TargetName="toggleBorder" Property="Background" Value="LightGray"/>
<Setter TargetName="path" Property="Fill">
<Setter.Value>
<LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
<GradientStop Color="Gray"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter TargetName="path" Property="Data">
<Setter.Value>
<GeometryGroup>
<GeometryGroup.Children>
<EllipseGeometry Center="13,12" RadiusX="9" RadiusY="9"/>
</GeometryGroup.Children>
</GeometryGroup>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ToggleButtonStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Width" Value="45"></Setter>
<Setter Property="Height" Value="20"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<!--定义视觉树-->
<Border x:Name="border" BorderThickness="1.5" CornerRadius="9" BorderBrush="#aaa" Background="#2790ff">
<Grid x:Name="togglebutton" HorizontalAlignment="Right" >
<Border Width="17" Height="17" CornerRadius="9" Background="White"/>
</Grid>
<!--阴影设置-->
<Border.Effect>
<DropShadowEffect Color="Gray" BlurRadius="5" ShadowDepth="0" Opacity="0.5" />
</Border.Effect>
</Border>
<!--定义触发器-->
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="false">
<Setter TargetName="border" Property="Background" Value="#ccc"/>
<Setter TargetName="togglebutton" Property="HorizontalAlignment" Value="Left"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--TextBlock样式-->
<Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Black"></Setter>
<Setter Property="FontSize" Value="26"></Setter>
<Setter Property="TextWrapping" Value="Wrap"></Setter>
<Setter Property="TextAlignment" Value="Center"></Setter>
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
<Setter Property="VerticalAlignment" Value="Bottom"></Setter>
<Setter Property="Height" Value="100"></Setter>
</Style>
<!--Tab样式-->
<SolidColorBrush x:Key="TabControl.BodyBackground" Color="#ffffff" />
<SolidColorBrush x:Key="TabControl.HeaderBackGround" Color="#ffffff" />
<SolidColorBrush x:Key="TabControl.ActivedHeaderBackground" Color="#FFA500" />
<SolidColorBrush x:Key="TabControl.BorderBrush" Color="#d3d3d3" />
<SolidColorBrush x:Key="TabControl.ActivedHeaderBorderBrush" Color="#FF8C00" />
<SolidColorBrush x:Key="TabItem.Foreground" Color="#000000" />
<SolidColorBrush x:Key="TabItem.ActivedForeground" Color="#ffffff" />
<Style x:Key="TabControlStyle" TargetType="{x:Type TabControl}" BasedOn="{StaticResource {x:Type TabControl}}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Height" Value="auto" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabControl}">
<Border Background="{StaticResource TabControl.BodyBackground}" BorderThickness="0" Margin="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border Name="Mask" Grid.Column="0" Background="{StaticResource TabControl.HeaderBackGround}"/>
<Border Grid.Column="0" Padding="0" Margin="0">
<TabPanel IsItemsHost="True">
<TabPanel.OpacityMask>
<VisualBrush Visual="{Binding ElementName=Mask}" />
</TabPanel.OpacityMask>
</TabPanel>
</Border>
<Border Grid.Column="1" Margin="0" BorderThickness="0,1,1,1" BorderBrush="{StaticResource TabControl.BorderBrush}" />
<Border Grid.Column="1">
<ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="TabItemStyle" TargetType="{x:Type TabItem}" BasedOn="{StaticResource {x:Type TabItem}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Border x:Name="bg" Background="{StaticResource TabControl.HeaderBackGround}" Margin="0" CornerRadius="2"
SnapsToDevicePixels="True" ClipToBounds="True" BorderThickness="1" BorderBrush="{StaticResource TabControl.BorderBrush}">
<TextBlock Style="{StaticResource TextBlockStyle}">
<ContentPresenter x:Name="contentPresenter"
ContentSource="Header"
Focusable="False"
Margin="0"
RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Header, RelativeSource={RelativeSource AncestorType=TabItem}}" TextWrapping="Wrap"></TextBlock>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</TextBlock>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="contentPresenter" Property="TabItem.Foreground" Value="{StaticResource TabItem.ActivedForeground}"/>
<Setter TargetName="bg" Property="TabItem.Background" Value="{StaticResource TabControl.ActivedHeaderBackground}"/>
<Setter TargetName="bg" Property="TabItem.BorderBrush" Value="{StaticResource TabControl.ActivedHeaderBorderBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 专门给报警界面使用 -->
<Style TargetType="{x:Type DataGridRow}" x:Key="AlarmMonitoringModelDataGrid" >
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding alarms_state}" Value="报警"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>-->
<Setter Property="Foreground" Value="#FF0000" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding alarms_state}" Value="警告"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>-->
<Setter Property="Foreground" Value="#CC9B00" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<DataTrigger Binding="{Binding alarms_state}" Value="恢复">
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>-->
<Setter Property="Foreground" Value="#449249" />
</DataTrigger>
</Style.Triggers>
</Style>
<!--报警示意图的按钮1-->
<Style TargetType="{x:Type Button}" x:Key="hiddenbtn">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Opacity" Value="0.55"/>
<Setter Property="BorderThickness" Value="0"/>
<!--<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.55"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="BorderBrush" Value="#5D6687"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Opacity" Value="1"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
</Style.Triggers>-->
</Style>
<!--报警示意图的按钮2-->
<KeySpline x:Key="KeySpline1">
0.4,0.1,0.6,0.9
</KeySpline>
<Style TargetType="{x:Type Button}" x:Key="alarmbtn">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Ellipse Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
Name="Ellipse1">
<!--<Ellipse.Effect>
<DropShadowEffect Opacity="1"
ShadowDepth="0"
Color="#FFC8BD"
BlurRadius="20"
Direction="2">
</DropShadowEffect>
</Ellipse.Effect>-->
<Ellipse.Fill>
<RadialGradientBrush SpreadMethod="Repeat">
<RadialGradientBrush.GradientStops>
<GradientStop Offset="0.00" Color="#FFFFFF" />
<GradientStop Offset="0.9" Color="#C24020" />
</RadialGradientBrush.GradientStops>
</RadialGradientBrush>
</Ellipse.Fill>
<Ellipse.Triggers>
<EventTrigger RoutedEvent="Ellipse.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<!--<ColorAnimationUsingKeyFrames Storyboard.TargetName="Ellipse1"
Storyboard.TargetProperty="Fill.GradientStops[0].Color"
RepeatBehavior="Forever"
AutoReverse="True">
<SplineColorKeyFrame KeyTime="0:0:1"
Value="Transparent"
KeySpline="{StaticResource KeySpline1}"/>
</ColorAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Ellipse1"
Storyboard.TargetProperty="Fill.GradientStops[1].Color"
RepeatBehavior="Forever"
AutoReverse="True">
<SplineColorKeyFrame KeyTime="0:0:1"
Value="Transparent"
KeySpline="{StaticResource KeySpline1}"/>
</ColorAnimationUsingKeyFrames>-->
<DoubleAnimation Storyboard.TargetName="Ellipse1" Storyboard.TargetProperty="Opacity"
From="1" To="0.1" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Ellipse.Triggers>
</Ellipse>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--报警示意图的提示框-->
<Style x:Key="ToolTipStyle" TargetType="ToolTip">
<Setter Property ="IsOpen" Value="False">
</Setter>
<Setter Property ="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Border x:Name="errorBorder" Background="#CC595959" BorderBrush="#99000000" BorderThickness="1" CornerRadius ="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin ="0" MaxWidth="320">
<Border.Effect>
<DropShadowEffect BlurRadius ="4" ShadowDepth="0"/>
</Border.Effect>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width ="Auto"/>
<ColumnDefinition Width ="*"/>
</Grid.ColumnDefinitions>
<Border Margin ="16,16,8,16" VerticalAlignment="Top">
<Path x:Name="path1" Grid.ColumnSpan="1" Data="M9.0789473,12.870737 L10.927632,12.870737 10.927632,14.5 9.0789473,14.5 z M9.0000001,5.9999999 L11,5.9999999 11,7.994543 10.526316,12.308322 9.4802633,12.308322 9.0000001,7.994543 z M9.9647158,1.8074455 C9.5912184,1.7923756 9.2860216,2.1402843 9.2860216,2.1402845 9.2860216,2.1402843 2.5977592,14.8926 2.2227221,15.46075 1.8476844,16.028899 2.5562553,16.218284 2.5562553,16.218284 2.5562553,16.218284 16.2035,16.218284 17.18278,16.218284 18.162063,16.218284 17.870029,15.460751 17.870029,15.460751 17.870029,15.460751 11.056506,2.8352754 10.494117,2.1197443 10.31837,1.8961406 10.134488,1.8142953 9.9647158,1.8074455 z M9.9331295,0.00021409988 C10.317457,0.0076069832 10.762559,0.20740509 11.244278,0.77299643 12.785778,2.5828881 19.97391,16.249695 19.97391,16.249695 19.97391,16.249695 20.318179,17.954408 18.505573,17.985971 16.692966,18.017535 1.5982747,17.985971 1.5982747,17.985971 1.5982747,17.985971 -0.27740097,18.206807 0.03512764,16.028899 0.3476572,13.850991 8.5362361,0.89893103 8.536236,0.8989315 8.5362361,0.89893103 9.0876089,-0.016049385 9.9331295,0.00021409988 z" Height="17" Stretch="Fill" Width="20" Visibility="Visible" Fill ="Red"/>
</Border>
<TextBlock x:Name="textBlock" Text="{TemplateBinding Content }" Margin="0,14,10,14" FontSize="14" Grid.Column ="1" TextWrapping="Wrap" Foreground="Red"/>
</Grid>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<!--时间输入框-->
<Style TargetType="{x:Type controls:SimpleTimeEditer}">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="#ececec"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:SimpleTimeEditer}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Height="{TemplateBinding Height}">
<Grid Margin="3 0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="PART_TXTHOUR" HorizontalContentAlignment="Center"
Cursor="Arrow" BorderThickness="0" SelectionBrush="White"
AutoWordSelection="False" Text="{Binding Hour,RelativeSource={RelativeSource TemplatedParent},StringFormat={}{0:00},UpdateSourceTrigger=PropertyChanged}"
Foreground="Black" Focusable="True" IsReadOnly="True" IsReadOnlyCaretVisible="False" VerticalAlignment="Center"/>
<TextBlock Text=":" VerticalAlignment="Center" Grid.Column="1"/>
<TextBox x:Name="PART_TXTMINUTE" HorizontalContentAlignment="Center"
Cursor="Arrow" Grid.Column="2" BorderThickness="0" AutoWordSelection="False"
Text="{Binding Minute,RelativeSource={RelativeSource TemplatedParent},StringFormat={}{0:00},UpdateSourceTrigger=PropertyChanged}"
Foreground="Black" Focusable="True" IsReadOnly="True" IsReadOnlyCaretVisible="False" VerticalAlignment="Center"/>
<TextBlock Text=":" VerticalAlignment="Center" Grid.Column="3"/>
<TextBox x:Name="PART_TXTSECOND" HorizontalContentAlignment="Center"
Cursor="Arrow" Grid.Column="4" BorderThickness="0" AutoWordSelection="False"
Text="{Binding Second,RelativeSource={RelativeSource TemplatedParent},StringFormat={}{0:00},UpdateSourceTrigger=PropertyChanged}"
Foreground="Black" Focusable="True" IsReadOnly="True" IsReadOnlyCaretVisible="False" VerticalAlignment="Center"/>
<TextBox x:Name="PART_TXT4" Grid.Column="5" Background="Transparent" BorderThickness="0" IsReadOnly="True" AutoWordSelection="False"
IsReadOnlyCaretVisible="False" Cursor="Arrow" />
<Grid Grid.Column="5" HorizontalAlignment="Right" x:Name="numIncrease" Visibility="{TemplateBinding NumIncreaseVisible}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button x:Name="PART_UP" Focusable="False" Width="16" Height="16" VerticalAlignment="Top">
<Button.Background>
<ImageBrush ImageSource="pack://application:,,,/StandardDomeNewApp;component/Images/UserControls/Up.png"/>
</Button.Background>
</Button>
<Button x:Name="PART_DOWN" Focusable="False" Width="16" Height="16" VerticalAlignment="Bottom" Grid.Row="1">
<Button.Background>
<ImageBrush ImageSource="pack://application:,,,/StandardDomeNewApp;component/Images/UserControls/Down.png"/>
</Button.Background>
</Button>
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--DataGrid列标题网格线-->
<Style x:Key="DataGridColumnHeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Height" Value="40"/>
<Setter Property="BorderThickness" Value="0.6"></Setter>
<!--设置边框笔刷BorderBrush-->
<Setter Property="BorderBrush">
<!--值-->
<Setter.Value>
<!--色刷Opacity透明度-->
<SolidColorBrush Color="Black" Opacity="1"></SolidColorBrush>
</Setter.Value>
</Setter>
</Style>
<!--DataGrid内容居中-->
<Style x:Key="DataGridCellStyle" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="TextAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<!--DataGridStyle标题显示类型-->
<Style x:Key="DataGridStyle" TargetType="DataGrid">
<Setter Property="HeadersVisibility" Value="Column" />
</Style>
</ResourceDictionary>
</Application.Resources>
</prism:PrismApplication>

View File

@@ -0,0 +1,164 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="DXThemeManager" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
</appSettings>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.28.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</entityFramework>
<!-- 数据库连接语句 cowain2023! -->
<connectionStrings>
<add name="SQLModel" connectionString="data source=172.26.12.249;initial catalog=cowain_standard;persist security info=True;user id=sa;password=Sa123;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<!--<add name="MySQLModel" connectionString="Data Source=127.0.0.1;port=3306;Initial Catalog=cowain_stove_6078;user id=root;password=cowain2023!;" providerName="MySql.Data.MySqlClient" />-->
<add name="MySQLModel" connectionString="Data Source=172.30.30.4;port=3306;Initial Catalog=cowain_stove_6078;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Google.Protobuf" publicKeyToken="a7d26565bac4d604" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.21.5.0" newVersion="3.21.5.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="K4os.Compression.LZ4.Streams" publicKeyToken="2186fa9121ef231d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.16.0" newVersion="1.2.16.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="BouncyCastle.Crypto" publicKeyToken="0e99375e54769942" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.9.0.0" newVersion="1.9.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="K4os.Hash.xxHash" publicKeyToken="32cd54395057cec3" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.7.0" newVersion="1.0.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="ControlzEx" publicKeyToken="69f1c32f803d307e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DryIoc" publicKeyToken="dfbf2bd50fcf7768" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.7.7.0" newVersion="4.7.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.15.0" newVersion="2.0.15.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.2.0" newVersion="4.2.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.2.0" newVersion="4.2.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.28.0" newVersion="3.1.28.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Encodings.Web" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNetCore.Http" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.22.0" newVersion="2.1.22.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.Pipelines" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.3" newVersion="6.0.0.3" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Cng" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.1.1" newVersion="4.3.1.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNetCore.Server.Kestrel.Core" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.25.0" newVersion="2.1.25.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Opc.Ua.Client" publicKeyToken="bfa7a73c5cf4b6e8" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.4.371.0" newVersion="1.4.371.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Opc.Ua.Core" publicKeyToken="bfa7a73c5cf4b6e8" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.4.371.0" newVersion="1.4.371.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<log4net>
<!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
<!-- Set root logger level to ERROR and its appenders -->
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileTracer" />
</root>
<!-- Print only messages of level DEBUG or above in the packages -->
<appender name="RollingFileTracer" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="Log/" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Composite" />
<param name="MaxSizeRollBackups" value="10" />
<param name="MaximumFileSize" value="10MB" />
<param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
<!--最小锁定模型以允许多个进程可以写入同一个文件-->
<param name="lockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
<param name="Encoding" value="utf-8" />
</appender>
</log4net>
<userSettings>
<DXThemeManager>
<setting name="ApplicationThemeName" serializeAs="String">
<value>Office2013</value>
</setting>
</DXThemeManager>
</userSettings>
</configuration>

View File

@@ -0,0 +1,599 @@
<prism:PrismApplication x:Class="StandardDomeNewApp.App"
xmlns:prism="http://prismlibrary.com/"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StandardDomeNewApp"
xmlns:controls="clr-namespace:StandardDomeNewApp.Modules"
>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--HandyControl-->
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
<!--Fluent-->
<ResourceDictionary Source="pack://application:,,,/Fluent;component/Themes/Generic.xaml" />
<ResourceDictionary Source="pack://application:,,,/Fluent;component/Themes/Themes/Light.Green.xaml" />
<!--<ResourceDictionary Source="pack://application:,,,/Fluent;component/Themes/Themes/Dark.Green.xaml" />-->
<!--AvalonDock-->
<ResourceDictionary Source="pack://application:,,,/AvalonDock;component/Themes/Generic.xaml" />
<ResourceDictionary Source="pack://application:,,,/AvalonDock.Themes.VS2013;component/LightBrushs.xaml" />
<!--<ResourceDictionary Source="pack://application:,,,/AvalonDock.Themes.VS2013;component/DarkBrushs.xaml" />-->
<ResourceDictionary Source="Language\en-US.xaml" />
<ResourceDictionary Source="Language\zh-CN.xaml" />
<ResourceDictionary Source="/StandardDomeNewApp;component/Modules/ComboBoxDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
<HierarchicalDataTemplate x:Key="ItemNode" ItemsSource="{Binding menuInfoModels,Mode=TwoWay}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button BorderThickness="0" Background="Transparent" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="-10,0,0,0" ToolTip="{Binding textValue,Mode=TwoWay}">
<Image Source="{Binding picPath,Mode=TwoWay}"/>
</Button>
<TextBlock Text="{Binding textValue,Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Left"
Foreground="{Binding foreGround,Mode=TwoWay}" FontSize="{Binding fontSize,Mode=TwoWay}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
<!--ToggleButton默认的样式-->
<Style x:Key="DefaultToggleSwitch" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<ControlTemplate.Resources>
<Storyboard x:Key="OnChecked">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.TargetName="path">
<EasingThicknessKeyFrame KeyTime="0" Value="40,0,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="OnUnchecked">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.TargetName="path">
<EasingThicknessKeyFrame KeyTime="0" Value="0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Border x:Name="toggleBorder"
CornerRadius="13"
Background="Green"
Width="60"
Height="26"
BorderThickness="1"
BorderBrush="Gray">
<Grid>
<Path x:Name="path">
<Path.Fill>
<LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
<GradientStop Color="White"/>
</LinearGradientBrush>
</Path.Fill>
<Path.Data>
<GeometryGroup>
<GeometryGroup.Children>
<EllipseGeometry Center="6,12" RadiusX="9" RadiusY="9"/>
</GeometryGroup.Children>
</GeometryGroup>
</Path.Data>
</Path>
</Grid>
</Border>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="ToggleButton.Checked">
<BeginStoryboard Storyboard="{StaticResource OnChecked}"/>
</EventTrigger>
<EventTrigger RoutedEvent="ToggleButton.Unchecked">
<BeginStoryboard Storyboard="{StaticResource OnUnchecked}"/>
</EventTrigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="DimGray"/>
<Setter TargetName="toggleBorder" Property="Background" Value="Green"/>
<Setter TargetName="toggleBorder" Property="BorderBrush" Value="Green"/>
</Trigger>
<Trigger Property="IsChecked" Value="False">
<Setter TargetName="toggleBorder" Property="Background" Value="LightGray"/>
<Setter TargetName="path" Property="Fill">
<Setter.Value>
<LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
<GradientStop Color="Gray"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter TargetName="path" Property="Data">
<Setter.Value>
<GeometryGroup>
<GeometryGroup.Children>
<EllipseGeometry Center="13,12" RadiusX="9" RadiusY="9"/>
</GeometryGroup.Children>
</GeometryGroup>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ToggleButtonStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Width" Value="45"></Setter>
<Setter Property="Height" Value="20"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<!--定义视觉树-->
<Border x:Name="border" BorderThickness="1.5" CornerRadius="9" BorderBrush="#aaa" Background="#2790ff">
<Grid x:Name="togglebutton" HorizontalAlignment="Right" >
<Border Width="17" Height="17" CornerRadius="9" Background="White"/>
</Grid>
<!--阴影设置-->
<Border.Effect>
<DropShadowEffect Color="Gray" BlurRadius="5" ShadowDepth="0" Opacity="0.5" />
</Border.Effect>
</Border>
<!--定义触发器-->
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="false">
<Setter TargetName="border" Property="Background" Value="#ccc"/>
<Setter TargetName="togglebutton" Property="HorizontalAlignment" Value="Left"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--TextBlock样式-->
<Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Black"></Setter>
<Setter Property="FontSize" Value="26"></Setter>
<Setter Property="TextWrapping" Value="Wrap"></Setter>
<Setter Property="TextAlignment" Value="Center"></Setter>
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
<Setter Property="VerticalAlignment" Value="Bottom"></Setter>
<Setter Property="Height" Value="100"></Setter>
</Style>
<!--Tab样式-->
<SolidColorBrush x:Key="TabControl.BodyBackground" Color="#ffffff" />
<SolidColorBrush x:Key="TabControl.HeaderBackGround" Color="#ffffff" />
<SolidColorBrush x:Key="TabControl.ActivedHeaderBackground" Color="#FFA500" />
<SolidColorBrush x:Key="TabControl.BorderBrush" Color="#d3d3d3" />
<SolidColorBrush x:Key="TabControl.ActivedHeaderBorderBrush" Color="#FF8C00" />
<SolidColorBrush x:Key="TabItem.Foreground" Color="#000000" />
<SolidColorBrush x:Key="TabItem.ActivedForeground" Color="#ffffff" />
<Style x:Key="TabControlStyle" TargetType="{x:Type TabControl}" BasedOn="{StaticResource {x:Type TabControl}}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Height" Value="auto" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabControl}">
<Border Background="{StaticResource TabControl.BodyBackground}" BorderThickness="0" Margin="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border Name="Mask" Grid.Column="0" Background="{StaticResource TabControl.HeaderBackGround}"/>
<Border Grid.Column="0" Padding="0" Margin="0">
<TabPanel IsItemsHost="True">
<TabPanel.OpacityMask>
<VisualBrush Visual="{Binding ElementName=Mask}" />
</TabPanel.OpacityMask>
</TabPanel>
</Border>
<Border Grid.Column="1" Margin="0" BorderThickness="0,1,1,1" BorderBrush="{StaticResource TabControl.BorderBrush}" />
<Border Grid.Column="1">
<ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="TabItemStyle" TargetType="{x:Type TabItem}" BasedOn="{StaticResource {x:Type TabItem}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Border x:Name="bg" Background="{StaticResource TabControl.HeaderBackGround}" Margin="0" CornerRadius="2"
SnapsToDevicePixels="True" ClipToBounds="True" BorderThickness="1" BorderBrush="{StaticResource TabControl.BorderBrush}">
<TextBlock Style="{StaticResource TextBlockStyle}">
<ContentPresenter x:Name="contentPresenter"
ContentSource="Header"
Focusable="False"
Margin="0"
RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Header, RelativeSource={RelativeSource AncestorType=TabItem}}" TextWrapping="Wrap"></TextBlock>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</TextBlock>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="contentPresenter" Property="TabItem.Foreground" Value="{StaticResource TabItem.ActivedForeground}"/>
<Setter TargetName="bg" Property="TabItem.Background" Value="{StaticResource TabControl.ActivedHeaderBackground}"/>
<Setter TargetName="bg" Property="TabItem.BorderBrush" Value="{StaticResource TabControl.ActivedHeaderBorderBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 专门给报警界面使用 -->
<Style TargetType="{x:Type DataGridRow}" x:Key="AlarmMonitoringModelDataGrid" >
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding alarms_state}" Value="报警"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>-->
<Setter Property="Foreground" Value="#FF0000" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding alarms_state}" Value="警告"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>-->
<Setter Property="Foreground" Value="#CC9B00" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<DataTrigger Binding="{Binding alarms_state}" Value="恢复">
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>-->
<Setter Property="Foreground" Value="#449249" />
</DataTrigger>
</Style.Triggers>
</Style>
<!--报警示意图的按钮1-->
<Style TargetType="{x:Type Button}" x:Key="hiddenbtn">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Opacity" Value="0.55"/>
<Setter Property="BorderThickness" Value="0"/>
<!--<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.55"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="BorderBrush" Value="#5D6687"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Opacity" Value="1"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
</Style.Triggers>-->
</Style>
<!--报警示意图的按钮2-->
<KeySpline x:Key="KeySpline1">
0.4,0.1,0.6,0.9
</KeySpline>
<Style TargetType="{x:Type Button}" x:Key="alarmbtn">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Ellipse Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
Name="Ellipse1">
<!--<Ellipse.Effect>
<DropShadowEffect Opacity="1"
ShadowDepth="0"
Color="#FFC8BD"
BlurRadius="20"
Direction="2">
</DropShadowEffect>
</Ellipse.Effect>-->
<Ellipse.Fill>
<RadialGradientBrush SpreadMethod="Repeat">
<RadialGradientBrush.GradientStops>
<GradientStop Offset="0.00" Color="#FFFFFF" />
<GradientStop Offset="0.9" Color="#C24020" />
</RadialGradientBrush.GradientStops>
</RadialGradientBrush>
</Ellipse.Fill>
<Ellipse.Triggers>
<EventTrigger RoutedEvent="Ellipse.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<!--<ColorAnimationUsingKeyFrames Storyboard.TargetName="Ellipse1"
Storyboard.TargetProperty="Fill.GradientStops[0].Color"
RepeatBehavior="Forever"
AutoReverse="True">
<SplineColorKeyFrame KeyTime="0:0:1"
Value="Transparent"
KeySpline="{StaticResource KeySpline1}"/>
</ColorAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Ellipse1"
Storyboard.TargetProperty="Fill.GradientStops[1].Color"
RepeatBehavior="Forever"
AutoReverse="True">
<SplineColorKeyFrame KeyTime="0:0:1"
Value="Transparent"
KeySpline="{StaticResource KeySpline1}"/>
</ColorAnimationUsingKeyFrames>-->
<DoubleAnimation Storyboard.TargetName="Ellipse1" Storyboard.TargetProperty="Opacity"
From="1" To="0.1" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Ellipse.Triggers>
</Ellipse>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--报警示意图的提示框-->
<Style x:Key="ToolTipStyle" TargetType="ToolTip">
<Setter Property ="IsOpen" Value="False">
</Setter>
<Setter Property ="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Border x:Name="errorBorder" Background="#CC595959" BorderBrush="#99000000" BorderThickness="1" CornerRadius ="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin ="0" MaxWidth="320">
<Border.Effect>
<DropShadowEffect BlurRadius ="4" ShadowDepth="0"/>
</Border.Effect>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width ="Auto"/>
<ColumnDefinition Width ="*"/>
</Grid.ColumnDefinitions>
<Border Margin ="16,16,8,16" VerticalAlignment="Top">
<Path x:Name="path1" Grid.ColumnSpan="1" Data="M9.0789473,12.870737 L10.927632,12.870737 10.927632,14.5 9.0789473,14.5 z M9.0000001,5.9999999 L11,5.9999999 11,7.994543 10.526316,12.308322 9.4802633,12.308322 9.0000001,7.994543 z M9.9647158,1.8074455 C9.5912184,1.7923756 9.2860216,2.1402843 9.2860216,2.1402845 9.2860216,2.1402843 2.5977592,14.8926 2.2227221,15.46075 1.8476844,16.028899 2.5562553,16.218284 2.5562553,16.218284 2.5562553,16.218284 16.2035,16.218284 17.18278,16.218284 18.162063,16.218284 17.870029,15.460751 17.870029,15.460751 17.870029,15.460751 11.056506,2.8352754 10.494117,2.1197443 10.31837,1.8961406 10.134488,1.8142953 9.9647158,1.8074455 z M9.9331295,0.00021409988 C10.317457,0.0076069832 10.762559,0.20740509 11.244278,0.77299643 12.785778,2.5828881 19.97391,16.249695 19.97391,16.249695 19.97391,16.249695 20.318179,17.954408 18.505573,17.985971 16.692966,18.017535 1.5982747,17.985971 1.5982747,17.985971 1.5982747,17.985971 -0.27740097,18.206807 0.03512764,16.028899 0.3476572,13.850991 8.5362361,0.89893103 8.536236,0.8989315 8.5362361,0.89893103 9.0876089,-0.016049385 9.9331295,0.00021409988 z" Height="17" Stretch="Fill" Width="20" Visibility="Visible" Fill ="Red"/>
</Border>
<TextBlock x:Name="textBlock" Text="{TemplateBinding Content }" Margin="0,14,10,14" FontSize="14" Grid.Column ="1" TextWrapping="Wrap" Foreground="Red"/>
</Grid>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<!--时间输入框-->
<Style TargetType="{x:Type controls:SimpleTimeEditer}">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="#ececec"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:SimpleTimeEditer}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Height="{TemplateBinding Height}">
<Grid Margin="3 0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="PART_TXTHOUR" HorizontalContentAlignment="Center"
Cursor="Arrow" BorderThickness="0" SelectionBrush="White"
AutoWordSelection="False" Text="{Binding Hour,RelativeSource={RelativeSource TemplatedParent},StringFormat={}{0:00},UpdateSourceTrigger=PropertyChanged}"
Foreground="Black" Focusable="True" IsReadOnly="True" IsReadOnlyCaretVisible="False" VerticalAlignment="Center"/>
<TextBlock Text=":" VerticalAlignment="Center" Grid.Column="1"/>
<TextBox x:Name="PART_TXTMINUTE" HorizontalContentAlignment="Center"
Cursor="Arrow" Grid.Column="2" BorderThickness="0" AutoWordSelection="False"
Text="{Binding Minute,RelativeSource={RelativeSource TemplatedParent},StringFormat={}{0:00},UpdateSourceTrigger=PropertyChanged}"
Foreground="Black" Focusable="True" IsReadOnly="True" IsReadOnlyCaretVisible="False" VerticalAlignment="Center"/>
<TextBlock Text=":" VerticalAlignment="Center" Grid.Column="3"/>
<TextBox x:Name="PART_TXTSECOND" HorizontalContentAlignment="Center"
Cursor="Arrow" Grid.Column="4" BorderThickness="0" AutoWordSelection="False"
Text="{Binding Second,RelativeSource={RelativeSource TemplatedParent},StringFormat={}{0:00},UpdateSourceTrigger=PropertyChanged}"
Foreground="Black" Focusable="True" IsReadOnly="True" IsReadOnlyCaretVisible="False" VerticalAlignment="Center"/>
<TextBox x:Name="PART_TXT4" Grid.Column="5" Background="Transparent" BorderThickness="0" IsReadOnly="True" AutoWordSelection="False"
IsReadOnlyCaretVisible="False" Cursor="Arrow" />
<Grid Grid.Column="5" HorizontalAlignment="Right" x:Name="numIncrease" Visibility="{TemplateBinding NumIncreaseVisible}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button x:Name="PART_UP" Focusable="False" Width="16" Height="16" VerticalAlignment="Top">
<Button.Background>
<ImageBrush ImageSource="pack://application:,,,/StandardDomeNewApp;component/Images/UserControls/Up.png"/>
</Button.Background>
</Button>
<Button x:Name="PART_DOWN" Focusable="False" Width="16" Height="16" VerticalAlignment="Bottom" Grid.Row="1">
<Button.Background>
<ImageBrush ImageSource="pack://application:,,,/StandardDomeNewApp;component/Images/UserControls/Down.png"/>
</Button.Background>
</Button>
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--DataGrid列标题网格线-->
<Style x:Key="DataGridColumnHeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Height" Value="40"/>
<Setter Property="BorderThickness" Value="0.6"></Setter>
<!--设置边框笔刷BorderBrush-->
<Setter Property="BorderBrush">
<!--值-->
<Setter.Value>
<!--色刷Opacity透明度-->
<SolidColorBrush Color="Black" Opacity="1"></SolidColorBrush>
</Setter.Value>
</Setter>
</Style>
<!--DataGrid内容居中-->
<Style x:Key="DataGridCellStyle" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="TextAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<!--DataGridStyle标题显示类型-->
<Style x:Key="DataGridStyle" TargetType="DataGrid">
<Setter Property="HeadersVisibility" Value="Column" />
</Style>
<ControlTemplate x:Key="MyScrollViewer" TargetType="{x:Type ScrollViewer}">
<!--View区域背景色-->
<Grid x:Name="Grid" Background="{TemplateBinding Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Rectangle x:Name="Corner" Grid.Column="1" Fill="White" Grid.Row="1"/>
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" CanHorizontallyScroll="False" CanVerticallyScroll="False" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="0" Margin="{TemplateBinding Padding}" Grid.Row="0"/>
<ScrollBar x:Name="PART_VerticalScrollBar" AutomationProperties.AutomationId="VerticalScrollBar" Cursor="Arrow" Grid.Column="1" Maximum="{TemplateBinding ScrollableHeight}" Minimum="0" Grid.Row="0" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}" Style="{DynamicResource MyScrollBarStyle}"/>
<ScrollBar x:Name="PART_HorizontalScrollBar" AutomationProperties.AutomationId="HorizontalScrollBar" Cursor="Arrow" Grid.Column="0" Maximum="{TemplateBinding ScrollableWidth}" Minimum="0" Orientation="Horizontal" Grid.Row="1" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}" Style="{DynamicResource MyScrollBarStyle}"/>
</Grid>
</ControlTemplate>
<SolidColorBrush x:Key="ScrollBarDisabledBackground" Color="#F4F4F4"/>
<Style x:Key="VerticalScrollBarPageButton" TargetType="{x:Type RepeatButton}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Rectangle Fill="{TemplateBinding Background}" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--滚动条颜色、圆角等设置-->
<Style x:Key="ScrollBarThumb" TargetType="{x:Type Thumb}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<!--滚动条颜色和圆角设置-->
<Rectangle Name="thumbRect" Fill="#03ffea" RadiusX="3" RadiusY="3"/>
<!--鼠标拉动滚动条时的颜色-->
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="DodgerBlue" TargetName="thumbRect" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="HorizontalScrollBarPageButton" TargetType="{x:Type RepeatButton}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Rectangle Fill="{TemplateBinding Background}" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyScrollBarStyle" TargetType="{x:Type ScrollBar}">
<Setter Property="Background" Value="AliceBlue"/>
<Setter Property="Stylus.IsPressAndHoldEnabled" Value="false"/>
<Setter Property="Stylus.IsFlicksEnabled" Value="false"/>
<!--滚动条宽度-->
<Setter Property="Width" Value="8"/>
<Setter Property="MinWidth" Value="6"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollBar}">
<!--滚动条背景色-->
<Grid x:Name="Bg" Background="#001f55" SnapsToDevicePixels="true" Width="8">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Track x:Name="PART_Track" IsDirectionReversed="true" IsEnabled="{TemplateBinding IsMouseOver}">
<Track.DecreaseRepeatButton>
<RepeatButton Command="{x:Static ScrollBar.PageUpCommand}" Style="{StaticResource VerticalScrollBarPageButton}"/>
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="{x:Static ScrollBar.PageDownCommand}" Style="{StaticResource VerticalScrollBarPageButton}"/>
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb Style="{StaticResource ScrollBarThumb}"/>
</Track.Thumb>
</Track>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bg" Value="{StaticResource ScrollBarDisabledBackground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
<Setter Property="Width" Value="Auto"/>
<Setter Property="MinWidth" Value="0"/>
<Setter Property="Height" Value="6"/>
<Setter Property="MinHeight" Value="6"/>
<Setter Property="Background" Value="AliceBlue"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollBar}">
<Grid x:Name="Bg" Background="Red" SnapsToDevicePixels="true">
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Track x:Name="PART_Track" IsEnabled="{TemplateBinding IsMouseOver}">
<Track.DecreaseRepeatButton>
<RepeatButton Command="{x:Static ScrollBar.PageLeftCommand}" Style="{StaticResource HorizontalScrollBarPageButton}"/>
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="{x:Static ScrollBar.PageRightCommand}" Style="{StaticResource HorizontalScrollBarPageButton}"/>
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb Style="{StaticResource ScrollBarThumb}" />
</Track.Thumb>
</Track>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bg" Value="{StaticResource ScrollBarDisabledBackground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</Application.Resources>
</prism:PrismApplication>

View File

@@ -0,0 +1,126 @@
using Prism.Ioc;
using Prism.Modularity;
using System.Windows;
using Prism.DryIoc;
using StandardDomeNewApp.View;
using System.Windows.Threading;
using System;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : PrismApplication
{
public App()
{
//首先注册开始和退出事件
this.Startup += new StartupEventHandler(App_Startup);
this.Exit += new ExitEventHandler(App_Exit);
}
protected override Window CreateShell()
{
return Container.Resolve<Login>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
}
protected override void OnStartup(StartupEventArgs e)
{
//var name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();
//using (Mutex m = new Mutex(true, name))
//{
// if (m.WaitOne(0, false))
// {
// }
// else
// {
// HandyControl.Controls.MessageBox.Error("程序已运行,请勿重复运行!", "错误");
// Shutdown();
// }
//}
//获取当前进程
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
//当前这个进程的有多少个和这个一样的
var names = System.Diagnostics.Process.GetProcessesByName(process.ProcessName);
if (names.Length > 1)
{
//有多个
HandyControl.Controls.MessageBox.Error(Util.CommonHelper.FindKeyValue("ProgramAlreadyRunning"));
Shutdown();
return;
}
base.OnStartup(e);
}
#region
private void App_Startup(object sender, StartupEventArgs e)
{
//UI线程未捕获异常处理事件
this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
//Task线程内未捕获异常处理事件
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
//非UI线程未捕获异常处理事件
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
private void App_Exit(object sender, ExitEventArgs e)
{
//程序退出时需要处理的业务
Util.CommonHelper.Fatal("App", "error App_Exit:");
}
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
try
{
Util.CommonHelper.Fatal("App", "error App_DispatcherUnhandledException:");
e.Handled = true; //把 Handled 属性设为true表示此异常已处理程序可以继续运行不会强制退出
// MessageBox.Show("UI线程异常:" + e.Exception.Message);
}
catch (Exception ex)
{
Util.CommonHelper.Fatal("App", $"error App_DispatcherUnhandledException:{ex}");
//此时程序出现严重异常,将强制结束退出
// HandyControl.Controls.MessageBox.Show("UI线程发生致命错误详情" + ex.Message);
}
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
StringBuilder sbEx = new StringBuilder();
if (e.IsTerminating)
{
sbEx.Append("非UI线程发生致命错误");
}
sbEx.Append("非UI线程异常");
if (e.ExceptionObject is Exception)
{
sbEx.Append(((Exception)e.ExceptionObject).Message);
}
else
{
sbEx.Append(e.ExceptionObject);
}
Util.CommonHelper.Fatal("App", $"error App_DispatcherUnhandledException:{sbEx.ToString()}");
// MessageBox.Show(sbEx.ToString());
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Util.CommonHelper.Fatal("App", $"error TaskScheduler_UnobservedTaskException:{e.ToString()}");
//task线程内未处理捕获
// HandyControl.Controls.MessageBox.Show("Task线程异常" + e.Exception.Message);
e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
}
#endregion
}
}

View File

@@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class AlarmConfig:Model.TAlarmsConfig
{
public List<Model.TAlarmsConfig> Query()
{
using (Mappering.DataBaseMappering SQLModel = new Mappering.DataBaseMappering())
{
var alarmConfigList = (from item in SQLModel.TAlarmsConfigs
select item).OrderBy(item=>item.PlcKey).ToList();
return alarmConfigList;
}
}
public List<DistinctPLC> DistinctPLCQuery()
{
using (Mappering.DataBaseMappering SQLModel = new Mappering.DataBaseMappering())
{
var distinctPLCList = (from item in SQLModel.TPlcRuleConfigs
select new DistinctPLC
{
PLCKey = item.PLCKey,
}).Distinct().OrderBy(item => item.PLCKey).ToList();
return distinctPLCList;
}
}
public bool Update()
{
using (Mappering.DataBaseMappering SQLModel = new Mappering.DataBaseMappering())
{
bool flag = false;
var alarmsConfigs = SQLModel.TAlarmsConfigs
.Where(item => item.ID == ID).FirstOrDefault();
alarmsConfigs.AlarmsDes = AlarmsDes;
alarmsConfigs.Address = Address;
alarmsConfigs.PlcKey = PlcKey;
alarmsConfigs.Offest = Offest;
alarmsConfigs.AlarmsState = AlarmsState;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public bool Add()
{
using (Mappering.DataBaseMappering SQLModel = new Mappering.DataBaseMappering())
{
try
{
bool flag = false;
Model.TAlarmsConfig alarmsConfig = new Model.TAlarmsConfig();
alarmsConfig.AlarmsDes = AlarmsDes;
alarmsConfig.Address = Address;
alarmsConfig.PlcKey = PlcKey;
alarmsConfig.Offest = Offest;
alarmsConfig.AlarmsState = AlarmsState;
SQLModel.TAlarmsConfigs.Add(alarmsConfig);
SQLModel.SaveChanges();
flag = true;
return flag;
}
catch (Exception ex)
{
Util.CommonHelper.Debug("AlarmConfig","Error 1:"+ex.Message);
return false;
}
}
}
public bool Delete()
{
using (Mappering.DataBaseMappering SQLModel = new Mappering.DataBaseMappering())
{
bool flag = false;
var alarmsConfigs = SQLModel.TAlarmsConfigs.Where(
item => item.ID==ID).ToList();
foreach (var item in alarmsConfigs)
{
SQLModel.TAlarmsConfigs.Remove(item);
}
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public List<WarningType> GetWarningType()
{
List<WarningType> warningTypes =new List<WarningType>()
{
new WarningType{ Type="警告"},
new WarningType{ Type="报警"},
};
return warningTypes;
}
public class DistinctPLC
{
public string PLCKey { get; set; }
}
public class WarningType
{
public string Type { get; set; }
}
}
}

View File

@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class AuthorizationControl : Model.TAuthorizationControl
{
public List<Model.TAuthorizationControl> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TAuthorizationControl> authrizationControlList
= new List<Model.TAuthorizationControl>();
authrizationControlList = SQLModel.AuthorizationControl
.OrderByDescending(item => item.Id).ToList();
return authrizationControlList;
}
}
public bool AuthorityQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
List<Model.TAuthorizationControl> authrizationControlList
= new List<Model.TAuthorizationControl>();
authrizationControlList = SQLModel.AuthorizationControl.Where(
item => item.Program==Program
&& item.Role==Role
&& item.ControlItem == ControlItem
&& item.Effect==true)
.OrderByDescending(item => item.Id).ToList();
if (authrizationControlList.Count > 0)
{
flag = true;
}
return flag;
}
}
public List<AuthorityItem> AuthorityTreeQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var authorityItems = from item in SQLModel.AuthorizationControl
where item.Role==Role && item.Program==Program
select new AuthorityItem
{
id=item.Id,
Effect = item.Effect.Value,
program=item.Program,
control_item=item.ControlItem,
role=item.Role,
ControlItemName=item.ControlItemName
};
return authorityItems.ToList();
}
}
public bool UpdateEffect()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var authorizationControl = SQLModel.AuthorizationControl.Where(
item => item.Id==Id).ToList().FirstOrDefault();
authorizationControl.Effect = Effect;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
Model.TAuthorizationControl authorizationControl = new Model.TAuthorizationControl();
authorizationControl.Program = Program;
authorizationControl.ControlItem =ControlItem;
authorizationControl.Role = Role;
SQLModel.AuthorizationControl.Add(authorizationControl);
SQLModel.SaveChanges();
return true;
}
}
//用于填充下拉列表
public List<DistinctRoleList> GetDistinctRoleList()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<DistinctRoleList> distinctRoleLists = new List<DistinctRoleList>();
distinctRoleLists = (from item in SQLModel.AuthorizationControl
select new DistinctRoleList
{
Role = item.Role
}).Distinct().OrderBy(item=>item.Role).ToList();
return distinctRoleLists;
}
}
public class DistinctRoleList
{
public string Role { get; set; }
}
public bool Delete()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var authorizationControl = SQLModel.AuthorizationControl.Where(
item => item.Role == Role).ToList();
foreach (var item in authorizationControl)
{
SQLModel.AuthorizationControl.Remove(item);
}
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
}
public class AuthorityItem: INotifyPropertyChanged
{
public int id { get; set; }
public string program { get; set; }
private bool effect;
public string control_item { get; set; }
public string ControlItemName { get; set; }//addwangzi
public string role { get; set; }
public List<AuthorityItem> Children { get; set; }
public AuthorityItem()
{
Children = new List<AuthorityItem>();
}
public bool Effect
{
get => effect;
set => SetProperty(ref effect,value);
}
protected void SetProperty<T>(ref T prop, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(prop, value) == false)
{
prop = value;
OnPropertyChanged(propertyName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class ControlPLCAddress:Model.TControlPlcAddress
{
public Model.TControlPlcAddress Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
Model.TControlPlcAddress controlPLC
= new Model.TControlPlcAddress();
controlPLC = SQLModel.TControlPlcAddress.Where(
item => item.ControlName==ControlName).FirstOrDefault();
return controlPLC;
}
}
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var controlPLCInfo = SQLModel.TControlPlcAddress
.Where(item => item.ControlName == ControlName).FirstOrDefault();
controlPLCInfo.Description = Description;
controlPLCInfo.PlcFilterKey = PlcFilterKey;
controlPLCInfo.Address = Address;
controlPLCInfo.Offset = Offset;
controlPLCInfo.Multiplier = Multiplier;
controlPLCInfo.OperationPara = OperationPara;
controlPLCInfo.Uom = Uom;
//cancelbywang2022-09-21 数据库没有这个字段
//controlPLCInfo.RoomCode = RoomCode;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class CustomList:Model.TCustomList
{
public List<Model.TCustomList> GetList()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TCustomList> customList = new List<Model.TCustomList>();
customList = SQLModel.TCustomList.Where(
item=>item.ListName.Contains(ListName)).OrderBy(item => item.ListContent).ToList();
return customList;
}
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class KeyValue
{
public string FindValue(string Key)
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TKeyValue> keyValues = new List<Model.TKeyValue>();
keyValues = SQLModel.TKeyValue.Where(item=>item.KeyC== Key).ToList();//Take 取前100条
return keyValues.FirstOrDefault().ValueC;
}
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class Log:Model.TLog
{
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
Model.TLog log = new Model.TLog();
log.LogText = LogText;
log.LogLevel = LogLevel;
log.LogDatetime = DateTime.Now;
SQLModel.log.Add(log);
SQLModel.SaveChanges();
return true;
}
}
//拿到最近100条
public List<Model.TLog> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TLog> logList = new List<Model.TLog>();
logList = SQLModel.log.OrderByDescending(item => item.Id).Take(100).ToList();//Take 取前100条
return logList;
}
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class Log:Model.TLog
{
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
Model.TLog log = new Model.TLog();
log.LogText = LogText;
log.LogLevel = LogLevel; // log_level;
log.LogDatetime = DateTime.Now;
SQLModel.log.Add(log);
SQLModel.SaveChanges();
return true;
}
}
//拿到最近100条
public List<Model.TLog> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TLog> logList = new List<Model.TLog>();
logList = SQLModel.log.OrderByDescending(item => item.Id).Take(100).ToList();//Take 取前100条
return logList;
}
}
}
}

View File

@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
class MachineAddress : Model.TMachineAddress
{
public List<Model.TMachineAddress> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineAddress> machineList = new List<Model.TMachineAddress>();
machineList = SQLModel.TMachineAddress.ToList();
return machineList;
}
}
public List<Model.TMachineAddress> QuerySome()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineAddress> positionList = new List<Model.TMachineAddress>();
positionList = (from item in SQLModel.TMachineAddress.
Where(item => item.LayerNo.Equals(LayerNo))
select item).ToList();
return positionList;
}
}
public List<Model.TMachineAddress> QueryPlcKey()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineAddress> positionList = new List<Model.TMachineAddress>();
positionList = (from item in SQLModel.TMachineAddress.
Where(item => item.KeyValue.Equals(KeyValue))
select item).ToList();
//var position = from machine in
// positionList
// select machine;
//string palletCode = (position.FirstOrDefault()).PalletCode;
return positionList;
}
}
public List<Model.TMachineAddress> QueryCavityNo()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineAddress> addressList = new List<Model.TMachineAddress>();
addressList = (from item in SQLModel.TMachineAddress.
Where(item => item.CavityNo.Equals(CavityNo))
select item).ToList();
return addressList;
}
}
//public string QueryPalletCode()
//{
// using (Model.SQLModel SQLModel = new Model.SQLModel())
// {
// List<Model.TMachineAddress> positionList = new List<Model.TMachineAddress>();
// positionList = (from item in SQLModel.TMachineAddress.
// Where(item => item.KeyValue.Equals(KeyValue))
// select item).ToList();
// var position = from machine in
// positionList
// select machine;
// string palletCode = (position.FirstOrDefault()).PalletCode;
// return palletCode;
// }
//}
public List<MachineDicModel> DistinctQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var machineDicList = (from item in SQLModel.TMachineAddress
select new MachineDicModel
{
PlcKey = item.PlcKey,
CavityNo = item.CavityNo
}
).Distinct().ToList();
return machineDicList;
}
}
public class MachineDicModel
{
public string PlcKey { get; set; }
public string CavityNo { get; set; }
}
}
}

View File

@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class MachineState : Model.TMachineState
{
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var paller = SQLModel.TMachineState.Where(item => item.LayerNo == LayerNo).FirstOrDefault();
paller.LayerNo = LayerNo;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public List<Model.TMachineState> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineState> machineList = new List<Model.TMachineState>();
machineList = SQLModel.TMachineState.ToList();
return machineList;
}
}
public List<Model.TMachineState> QuerySome()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineState> positionList = new List<Model.TMachineState>();
positionList = (from item in SQLModel.TMachineState.
Where(item => item.LayerName.Equals(LayerName))
select item).ToList();
return positionList;
}
}
public List<Model.TMachineState> QueryPlcKey()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineState> positionList = new List<Model.TMachineState>();
positionList = (from item in SQLModel.TMachineState.
Where(item => item.KeyValue.Equals(KeyValue))
select item).ToList();
//var position = from machine in
// positionList
// select machine;
//string palletCode = (position.FirstOrDefault()).PalletCode;
return positionList;
}
}
public string QueryPalletCode()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TMachineState> positionList = new List<Model.TMachineState>();
positionList = (from item in SQLModel.TMachineState.
Where(item => item.KeyValue.Equals(KeyValue))
select item).ToList();
var position = from machine in
positionList
select machine;
string palletCode = (position.FirstOrDefault()).PalletCode;
return palletCode;
}
}
public List<MachineDicModel> DistinctQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var machineDicList = (from item in SQLModel.TMachineState.Where(item=>item.Line==Line
)
select new MachineDicModel
{
PlcKey = item.PlcKey,
Stove = item.Stove
}
).Distinct().ToList();
return machineDicList;
}
}
public List<MachineDicModel> DistinctQueryall()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var machineDicList = (from item in SQLModel.TMachineState
select new MachineDicModel
{
PlcKey = item.PlcKey,
Stove = item.Stove
}
).Distinct().ToList();
return machineDicList;
}
}
public class MachineDicModel
{
public string PlcKey { get; set; }
public string Stove { get; set; }
}
}
}

View File

@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class OperationDetail : Model.TOperationDetail
{
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
try
{
Model.TOperationDetail operationDetail = new Model.TOperationDetail();
operationDetail.OperationCode = OperationCode;
operationDetail.CreateDatetime = DateTime.Now;
SQLModel.OperationDetail.Add(operationDetail);
SQLModel.SaveChanges();
return true;
}
catch (Exception ex)
{
Util.CommonHelper.Fatal("OperationDetail","Error 1"+ex.ToString());
return false;
}
}
}
public bool Delete()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var operationDetailList = SQLModel.OperationDetail.Where(
item => item.OperationCode == OperationCode).ToList();
foreach (var item in operationDetailList)
{
SQLModel.OperationDetail.Remove(item);
}
SQLModel.SaveChanges();
return true;
}
}
public List<OperationCodes> GetDistinctOperationTable()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var distinctOperationCodeList = (
from item in SQLModel.OperationDetail
select new OperationCodes
{
Operation = item.OperationCode
}
).ToList().OrderBy(item => item.Operation).ToList();
return distinctOperationCodeList;
}
}
public class OperationCodes
{
public string Operation { get; set; }
}
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var operationDetail = SQLModel.OperationDetail
.Where(item => item.OperationCode == OperationCode)
.FirstOrDefault();
operationDetail.OperationCode = OperationCode;
SQLModel.SaveChanges();
return true;
}
}
public List<Model.TOperationDetail> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TOperationDetail> operationDetailList = new List<Model.TOperationDetail>();
operationDetailList = SQLModel.OperationDetail.Where(
item => item.OperationCode.Contains(OperationCode))
.OrderByDescending(item=>item.Id).Take(300).ToList();
return operationDetailList;
}
}
}
}

View File

@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class OperationPara : Model.TOperationPara
{
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
try
{
Model.TOperationPara operation = new Model.TOperationPara();
operation.OperationCode = OperationCode;
operation.OperationParaName = OperationParaName;
operation.OperationValue = OperationValue;
SQLModel.OperationPara.Add(operation);
SQLModel.SaveChanges();
return true;
}
catch (Exception)
{
return false;
throw;
}
}
}
public List<OperationCodeModel> DistinctQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var operationParaList = (from item in SQLModel.OperationPara
select new OperationCodeModel
{
OperationCode = item.OperationCode
}
).Distinct().ToList();
return operationParaList;
}
}
public bool Delete()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var operationParaList = SQLModel.OperationPara.Where(
item => item.OperationCode == OperationCode
&& item.OperationParaName == OperationParaName).ToList();
foreach (var item in operationParaList)
{
SQLModel.OperationPara.Remove(item);
}
SQLModel.SaveChanges();
return true;
}
}
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var operationParaList = SQLModel.OperationPara.Where(
item => item.OperationCode == OperationCode
&& item.OperationParaName == OperationParaName).ToList().FirstOrDefault();
if (operationParaList==null)
{
return false;
}
operationParaList.OperationValue = OperationValue;
SQLModel.SaveChanges();
return true;
}
}
public List<Model.TOperationPara> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TOperationPara> operationList= new List<Model.TOperationPara>();
operationList = SQLModel.OperationPara.Where(
item => item.OperationCode==OperationCode)
.OrderByDescending(item => item.OperationParaName).Take(300).ToList();
return operationList;
}
}
public List<Model.TOperationPara> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TOperationPara> operationList = new List<Model.TOperationPara>();
operationList = SQLModel.OperationPara.Where(
item => item.OperationParaType == "Vacuum" || item.OperationParaType== "Anemometer")
.ToList();
return operationList;
}
}
}
public class OperationCodeModel
{
public string OperationCode { set; get; }
}
}

View File

@@ -0,0 +1,201 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class Pallet : Model.TPallet
{
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
Model.TPallet pallet = new Model.TPallet();
pallet.PalletCode = PalletCode;
pallet.PalletName = PalletName;
pallet.PalletStatus = 10;
pallet.PalletStatusName = "空闲";
SQLModel.TPallet.Add(pallet);
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var paller = SQLModel.TPallet.Where(item => item.PalletCode == PalletCode).FirstOrDefault();
paller.PalletName = PalletName;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public bool UpdatePisition()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var paller = SQLModel.TPallet.Where(item => item.PalletCode == PalletCode).FirstOrDefault();
paller.PositionDescribe = PositionDescribe;
paller.PalletPosition = PalletPosition;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public List<Model.TPallet> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = SQLModel.TPallet.Where(item => item.PalletCode.Contains(PalletCode)
|| item.PalletName.Contains(PalletName)).OrderBy(item => item.ID).ToList();
return palletList;
}
}
public List<Model.TPallet> statusQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = (from item in SQLModel.TPallet.
Where(item => item.PalletStatus.Equals(PalletStatus))
select item).ToList();
return palletList;
}
}
/// <summary>
/// 正在扫码的
/// </summary>
/// <returns></returns>
public List<Model.TPallet> statusLineQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = (from item in SQLModel.TPallet.
Where(item => item.PalletStatus.Equals(PalletStatus))
select item).ToList();
return palletList;
}
}
public List<Model.TPallet> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = SQLModel.TPallet.ToList();
return palletList;
}
}
public List<Model.TPallet> QuerySome()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList =( from item in SQLModel.TPallet.
Where(item => item.PalletCode.Equals(PalletCode))
select item).ToList();
return palletList;
}
}
public List<Model.TPallet> QuerySomeWater()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = (from item in SQLModel.TPallet.
Where(item => item.PalletCode==PalletCode&&item.WaterResult==WaterResult)
select item).ToList();
return palletList;
}
}
/// <summary>
/// 查空闲的
/// </summary>
/// <returns></returns>
public List<Model.TPallet> QueryNotEquals()
{
string line = "2";
if(Line=="2")
{
line = "1";
}
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = (from item in SQLModel.TPallet.
Where(item => !item.Line.Equals(line)&&item.PalletStatus.Equals(10))
select item).ToList();
return palletList;
}
}
public List<Model.TPallet> QueryWater()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TPallet> palletList = new List<Model.TPallet>();
palletList = (from item in SQLModel.TPallet.
Where(item => item.WaterResult.Equals(WaterResult))
select item).ToList();
return palletList;
}
}
public List<PalletDicModel> ByDistinctQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var palletDicList = (from item in SQLModel.TPallet.
Where(item => item.PalletCode.Equals(PalletCode))
select new PalletDicModel
{
PalletCode = item.PalletCode,
PalletName = item.PalletName,
OperationCode=item.OperationCode
}
).Distinct().ToList();
return palletDicList;
}
}
public bool Delete()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var paller = SQLModel.TPallet.Where(
item => item.PalletCode == PalletCode).ToList();
foreach (var item in paller)
{
SQLModel.TPallet.Remove(item);
}
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public class PalletDicModel
{
public string PalletCode { get; set; }
public string PalletName { get; set; }
public string OperationCode { get; set; }
}
}
}

View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class PalletCode:Model.TPalletCode
{
public List<Model.TPalletCode> Query()
{
using (Model.SQLModel sQLModel=new Model.SQLModel ())
{
List<Model.TPalletCode> palletCodeList = new List<Model.TPalletCode> ();
palletCodeList = sQLModel.TPalletCode.
Where(item=>item.PalletCode.Equals(PalletCode)).ToList();
return palletCodeList;
}
}
public List<Model.TPalletCode> QueryAll()
{
using (Model.SQLModel sQLModel = new Model.SQLModel())
{
List<Model.TPalletCode> palletCodeList = new List<Model.TPalletCode>();
palletCodeList = sQLModel.TPalletCode.ToList();
return palletCodeList;
}
}
public bool Delete()
{
using (Model.SQLModel sQLModel = new Model.SQLModel())
{
bool flag = false;
List<Model.TPalletCode> palletCodeList = new List<Model.TPalletCode>();
palletCodeList = sQLModel.TPalletCode.
Where(item => item.BatteryCode.Equals(BatteryCode)).ToList();
foreach (var item in palletCodeList)
{
sQLModel.TPalletCode.Remove(item);
}
sQLModel.SaveChanges();
flag = true;
return flag;
}
}
public int QueryRowCount()
{
using (Model.SQLModel sQLModel = new Model.SQLModel())
{
List<Model.TPalletCode> palletCodeList = new List<Model.TPalletCode>();
palletCodeList = sQLModel.TPalletCode.
Where(item => item.PalletCode.Equals(PalletCode)).ToList();
int rowCount = palletCodeList.Count();
return rowCount;
}
}
}
}

View File

@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class ProductionInformation : Model.TProductionInformation
{
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
try
{
Model.TProductionInformation productionInformation = new Model.TProductionInformation();
productionInformation.JobNum = JobNum;
productionInformation.Operation = Operation;
productionInformation.ProductionDatetime = DateTime.Now;
SQLModel.ProductionInformation.Add(productionInformation);
SQLModel.SaveChanges();
UpdateCurrentProduct();
return true;
}
catch (Exception ex)
{
Util.CommonHelper.Fatal("ProductionInformation","Error 1:"+ex.Message);
return false;
}
}
}
public bool Delete()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var productionInformation = SQLModel.ProductionInformation.Where(
item => item.JobNum == JobNum).ToList();
foreach (var item in productionInformation)
{
if (item.CurrentProduct)
{
return flag;
}
SQLModel.ProductionInformation.Remove(item);
}
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public List<Model.TProductionInformation> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var productionInformationList = SQLModel.ProductionInformation
.Where(item=>item.JobNum.Contains(JobNum))
.OrderByDescending(item => item.Id).Take(100).ToList();
return productionInformationList;
}
}
public List<Model.TProductionInformation> CurrentProductQuery()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
var productionInformationList = SQLModel.ProductionInformation
.Where(item=>item.CurrentProduct==true).OrderByDescending(item => item.Id).Take(100).ToList();
return productionInformationList;
}
}
public bool UpdateCurrentProduct()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
//把当前工单更新为正在生产,把其他工单更新为没有正在生产
var productionInformation = SQLModel.ProductionInformation.Where(
item => item.JobNum == JobNum).ToList();
foreach (var item in productionInformation)
{
item.CurrentProduct = true;
}
SQLModel.SaveChanges();
//把其他工单更新为没有正在生产
var productionInformation2 = SQLModel.ProductionInformation.Where(
item => item.JobNum != JobNum).ToList();
foreach (var item in productionInformation2)
{
item.CurrentProduct = false;
}
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class StepPara:Model.TStepPara
{
public List<Model.TStepPara> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TStepPara> waterSampleList = new List<Model.TStepPara>();
waterSampleList = SQLModel.TStepPara.ToList();
return waterSampleList;
}
}
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class StepParaValue:Model.TStepParaValue
{
public List<Model.TStepParaValue> queryALl()
{
using (Model.SQLModel sqlModel = new Model.SQLModel())
{
List<Model.TStepParaValue> stepParaValueList = new List<Model.TStepParaValue>();
stepParaValueList = sqlModel.TStepParaValue.ToList();
return stepParaValueList;
}
}
public List<Model.TStepParaValue> querybyCavityNo()
{
using (Model.SQLModel sqlModel = new Model.SQLModel())
{
List<Model.TStepParaValue> stepParaValueList = new List<Model.TStepParaValue>();
stepParaValueList = sqlModel.TStepParaValue.Where(item => item.CavityNo == CavityNo).ToList();
return stepParaValueList;
}
}
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
public class ToMES
{
public class SendHeader
{
public string Cmd { get; set; }
public string Status { get; set; }
public string DevNumber { get; set; }
public string Update { get; set; }
public string Sign { get; set; }
public List<SendDtl> DataList = new List<SendDtl>();
}
public class SendDtl
{
public string DataPreporty { get; set; }
public string DataValue { get; set; }
}
public void TCPSendMessage(string IP,int port,string ToMESString)
{
Socket ClientSocket;
IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
ClientSocket.Connect(endPoint); //与远程主机建立连接
byte[] message = Encoding.ASCII.GetBytes(ToMESString);
ClientSocket.Send(message);
ClientSocket.Close();
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL.Trace
{
public class ProductTracking
{
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class Translate : Model.translate
{
public void Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.translate> translateList = new List<Model.translate>();
translateList = SQLModel.translate
.Where(item => item.control_name.Contains(control_name)).ToList();
chinese = translateList[0].chinese;
english= translateList[0].english;
}
}
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class User:Model.TUserFile
{
//万能密码 cowain 2022
public bool Login()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var userList = SQLModel.UserFile.Where(
item => item.UserId == UserId
&& item.Password == Password
&& item.Valid == "Y").ToList();
if (userList.Count == 1)
{
this.Role = userList[0].Role;
flag = true;
}
return flag;
}
}
public bool ModifyPassword(string newPassword)
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var userList = SQLModel.UserFile.Where(item => item.UserId == UserId).FirstOrDefault();
userList.Password = newPassword;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var user = SQLModel.UserFile.Where(item => item.UserId == UserId).FirstOrDefault();
user.UserName = UserName;
user.Role = Role;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public List<Model.TUserFile> Query()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TUserFile> userList = new List<Model.TUserFile>();
userList = SQLModel.UserFile.Where(item => item.UserId.Contains(UserId)
&& item.UserName.Contains(UserName)).OrderBy(item => item.Id).ToList();
return userList;
}
}
public bool SetValid(string validChar)
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var userList = SQLModel.UserFile.Where(item => item.UserId == UserId).FirstOrDefault();
userList.Valid = validChar;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
public bool Add()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
Model.TUserFile user = new Model.TUserFile();
user.UserId = UserId;
user.UserName = UserName;
user.Role = Role;
user.Password = Util.SecurityHelper.MD5Encrypt(Password);// Util.SecurityHelper.MD5Encrypt("123456");
user.Valid = "Y";
SQLModel.UserFile.Add(user);
SQLModel.SaveChanges();
return true;
}
}
public bool CowainPassword()
{
//password='cowain2022'
if (UserId == "cowain" && Password == "3A824154B16ED7DAB899BF000B80EEEE")
{
return true;
}
else
{
return false;
}
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace StandardDomeNewApp.BLL
{
[NotMapped]
public class WaterSample : Model.TWaterSample
{
public List<Model.TWaterSample> QueryAll()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TWaterSample> waterSampleList = new List<Model.TWaterSample>();
waterSampleList = SQLModel.TWaterSample.ToList();
return waterSampleList;
}
}
public List<Model.TWaterSample> QuerySome()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
List<Model.TWaterSample> waterSampleList = new List<Model.TWaterSample>();
waterSampleList = (from item in SQLModel.TWaterSample.
Where(item => item.WaterResult.Equals(WaterResult))
select item).ToList();
return waterSampleList;
}
}
public bool Update()
{
using (Model.SQLModel SQLModel = new Model.SQLModel())
{
bool flag = false;
var sample = SQLModel.TWaterSample.Where(item => item.BatteryCode == BatteryCode).FirstOrDefault();
sample.WaterResult = WaterResult;
SQLModel.SaveChanges();
flag = true;
return flag;
}
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.ElectronicScale.ElectronicScaleHandler
{
public class ElectronicBalanceJudgment
{
/// <summary>
/// 判断结果描述
/// </summary>
public string JudgmentResultInfo { set; get; }
/// <summary>
/// 判断结果
/// </summary>
public bool JudgmentResult { set; get; }
}
public abstract class IElectronicBalanceHandler
{
/// <summary>
/// ok返回
/// </summary>
protected ElectronicBalanceJudgment OKResult { set; get; } = new ElectronicBalanceJudgment
{
JudgmentResult = true,
JudgmentResultInfo = Core.SysEnumInfon.WeightJudgmentResultType..ToString()
};
/// <summary>
/// 错误的值
/// </summary>
public static double ErrorValue { set; get; } = -0.000529;
/// <summary>
/// 比如 注液前重量设定值,注液前重量偏移值 注液后重量设定值,注液后重量偏移值 注液量设定值,注液量偏移值 注液前重量最大值,注液前重量最小值 注液后重量最大值,注液后重量最小值 注液量最大值,注液量最小值
/// </summary>
public abstract void InitConfig(double[] setparameters = null);
/// <summary>
/// 判断方法(判断传入的重量)
/// </summary>
/// <returns></returns>
public abstract ElectronicBalanceJudgment JudgeFunc(double val);
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.ElectronicScale.ElectronicScaleHandler
{
public class SetOffsetJudgment : IElectronicBalanceHandler
{
/// <summary>
/// 设定值
/// </summary>
public double SetPData { set; get; }
/// <summary>
/// 偏移值
/// </summary>
public double OffsetPData { set; get; }
public override void InitConfig(double[] setparameters = null)
{
if (setparameters?.Length > 1)
{
SetPData = setparameters[0];
OffsetPData = setparameters[1];
}
else
{
SetPData = ErrorValue;
OffsetPData = ErrorValue;
}
}
public override ElectronicBalanceJudgment JudgeFunc(double val)
{
if (SetPData == ErrorValue || OffsetPData == ErrorValue)
{
//返回ok
return OKResult;
}
var max = SetPData + OffsetPData;
var min = SetPData - OffsetPData;
if (val > max)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(Core.SysEnumInfon.WeightJudgmentResultType..ToString());
stringBuilder.Append("|当前值超出了设定最大值范围!详情:当前值【");
stringBuilder.Append(val.ToString());
stringBuilder.Append("】、最大值【");
stringBuilder.Append(max.ToString());
stringBuilder.Append("】 ");
return new ElectronicBalanceJudgment
{
JudgmentResult = false,
JudgmentResultInfo = stringBuilder.ToString()
};
}
else if (val < min)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(Core.SysEnumInfon.WeightJudgmentResultType..ToString());
stringBuilder.Append("|当前值超出了设定最大值范围!详情:当前值【");
stringBuilder.Append("当前值超出了设定最小值范围!详情:当前值【");
stringBuilder.Append(val.ToString());
stringBuilder.Append("】、最小值【");
stringBuilder.Append(min.ToString());
stringBuilder.Append("】 ");
return new ElectronicBalanceJudgment
{
JudgmentResult = false,
JudgmentResultInfo = stringBuilder.ToString()
};
}
return OKResult;
}
}
}

View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.ElectronicScale.ElectronicScaleHandler
{
public class UpperLowerLimitJudgment : IElectronicBalanceHandler
{
public double MaxPData { set; get; }
public double MinPData { set; get; }
public override void InitConfig(double[] setparameters)
{
if (setparameters?.Length > 1)
{
MaxPData = setparameters[0];
MinPData = setparameters[1];
}
else
{
MaxPData = ErrorValue;
MinPData = ErrorValue;
}
}
public override ElectronicBalanceJudgment JudgeFunc(double val)
{
if (MaxPData == ErrorValue || MinPData == ErrorValue)
{
//返回ok
return OKResult;
}
var max = MaxPData;
var min = MinPData;
if (val > max)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(Core.SysEnumInfon.WeightJudgmentResultType..ToString());
stringBuilder.Append("|当前值超出了设定最大值范围!详情:当前值【");
stringBuilder.Append(val.ToString());
stringBuilder.Append("】、最大值【");
stringBuilder.Append(max.ToString());
stringBuilder.Append("】 ");
return new ElectronicBalanceJudgment
{
JudgmentResult = false,
JudgmentResultInfo = stringBuilder.ToString()
};
}
else if (val < min)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(Core.SysEnumInfon.WeightJudgmentResultType..ToString());
stringBuilder.Append("|当前值超出了设定最大值范围!详情:当前值【");
stringBuilder.Append(val.ToString());
stringBuilder.Append("】、最小值【");
stringBuilder.Append(min.ToString());
stringBuilder.Append("】 ");
return new ElectronicBalanceJudgment
{
JudgmentResult = false,
JudgmentResultInfo = stringBuilder.ToString()
};
}
return OKResult;
}
}
}

View File

@@ -0,0 +1,251 @@
using StandardDomeNewApp.Communication.SerialPorts;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.ElectronicScale
{
public class ElectronicScale_SeriaPort : IElectronicBalance
{
/// <summary>
/// 参数模型
/// </summary>
private ElectronicScaleModel configModel { set; get; }
/// <summary>
/// 串口对象
/// </summary>
private SeriaPortController seriaPortController { set; get; }
/// <summary>
/// 接收的数据缓存
/// </summary>
private string DataCache { set; get; } = string.Empty;
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
/// <summary>
/// 锁对象
/// </summary>
private readonly Mutex _mutexLock = new Mutex();
/// <summary>
/// 防止读取时的原子级异常
/// </summary>
/// <param name="data"></param>
private void SetDataCache(string data)
{
_mutexLock.WaitOne();
try
{
if (string.IsNullOrEmpty(data))
{
DataCache = string.Empty;
}
else
{
DataCache += data;
}
}
finally
{
_mutexLock.ReleaseMutex();
}
}
private string GetDataCache()
{
_mutexLock.WaitOne();
try
{
return DataCache;
}
finally
{
_mutexLock.ReleaseMutex();
}
}
public override void Build(object config)
{
if (config is ElectronicScaleModel model)
{
configModel = model;
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
public override bool Connect()
{
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
seriaPortController = contentCache.GetContent<SeriaPortController>(configModel.ProtocolKey);
if (seriaPortController == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的串口对象!", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
seriaPortController.RawDataAction = RawData_Receive;
IsConnect = true;
oneEncoding = seriaPortController.encoding;
return true;
}
public override ElectronicBalanceResult ReadWeight()
{
return ReadWeight(null);
}
public override ElectronicBalanceResult ReadWeight(string keypar)
{
//错误数据
var model = ErrorData;
if (IsUseSimulationData)
{
//模拟数据
return SimulatedData;
}
for (int i = 0; i < configInfoModel.MaxReadCount; i++)
{
if (!string.IsNullOrEmpty(configModel.Command))
{
//命令不为空 发送命令
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
seriaPortController.Send(command + Environment.NewLine);
}
else
{
seriaPortController.Send(command);
}
}
//开始接收数据
IsAllowReceive = true;
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
break;
}
var info = GetDataCache();
if (regex != null)
{
if (!string.IsNullOrEmpty(info))
{
var match = regex.Match(info);
if (match.Success)
{
//去头去尾
string str = match.Value;
var arrayconnand = configModel.Command.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
info = str;
}
}
}
if (!string.IsNullOrEmpty(info))
{
if (double.TryParse(info, out double datavalue))
{
if (string.IsNullOrEmpty(keypar))
{
//无电芯键
model.WeighingWeight = datavalue;
model.LiquidInjectionVolume = 0;
if (OneElectronicBalanceHandler != null)
{
var resultmodel = OneElectronicBalanceHandler.JudgeFunc(model.WeighingWeight);
model.JudgmentResult = resultmodel.JudgmentResult;
model.JudgmentResultInfo = resultmodel.JudgmentResultInfo;
}
else
{
model.JudgmentResult = true;
model.JudgmentResultInfo = Core.SysEnumInfon.WeightJudgmentResultType..ToString();
}
}
else
{
//有电芯键 查询数据库计算注液量
model.WeighingWeight = datavalue;
using (var dbContext = new DataBaseMappering())
{
//获取注液量
}
if (OneElectronicBalanceHandler != null)
{
var resultmodel = OneElectronicBalanceHandler.JudgeFunc(model.WeighingWeight);
model.JudgmentResult = resultmodel.JudgmentResult;
model.JudgmentResultInfo += resultmodel.JudgmentResultInfo;
var resultmodel2 = OneElectronicBalanceHandler.JudgeFunc(model.LiquidInjectionVolume);
model.JudgmentResult = resultmodel2.JudgmentResult;
model.JudgmentResultInfo += resultmodel2.JudgmentResultInfo;
}
else
{
model.JudgmentResult = true;
model.JudgmentResultInfo = Core.SysEnumInfon.WeightJudgmentResultType..ToString();
}
}
break;
}
}
Thread.Sleep(1);
}
IsAllowReceive = false;
if (model.JudgmentResult)
{
break;
}
}
SetDataCache(string.Empty);
return model;
}
public override void ReConnect()
{
seriaPortController?.ReTryOpen();
}
public override bool UnConnect()
{
if (seriaPortController == null)
{
return false;
}
seriaPortController.Close();
IsConnect = false;
return true;
}
/// <summary>
/// 原始数据接收
/// </summary>
/// <param name="data"></param>
/// <param name="encoding"></param>
private void RawData_Receive(byte[] data, Encoding encoding)
{
if (!IsAllowReceive)
{
return;
}
SetDataCache(encoding.GetString(data));
}
}
}

View File

@@ -0,0 +1,117 @@
using StandardDomeNewApp.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.ElectronicScale
{
public abstract class IElectronicBalance
{
public IElectronicBalance()
{
ShowMessageAction = (s, b, t) =>
{
configInfoModel.ShowInvoke?.Invoke(s, b, t);
};
}
public class ElectronicBalanceResult
{
/// <summary>
/// 称重重量
/// </summary>
public double WeighingWeight { set; get; }
/// <summary>
/// 注液量
/// </summary>
public double LiquidInjectionVolume { set; get; }
/// <summary>
/// 判断结果描述
/// </summary>
public string JudgmentResultInfo { set; get; }
/// <summary>
/// 判断结果
/// </summary>
public bool JudgmentResult { set; get; }
}
public ElectronicBalanceResult SimulatedData { set; get; } = new ElectronicBalanceResult
{
JudgmentResultInfo = "模拟数据",
JudgmentResult = true
};
protected ElectronicBalanceResult ErrorData { set; get; } = new ElectronicBalanceResult
{
WeighingWeight = ErrorWeight,
LiquidInjectionVolume = ErrorWeight,
JudgmentResult = false,
JudgmentResultInfo = "未知错误"
};
/// <summary>
/// 判断对象 外部注入到对象里
/// </summary>
public ElectronicScaleHandler.IElectronicBalanceHandler OneElectronicBalanceHandler { set; get; }
/// <summary>
/// 错误重量
/// </summary>
public static readonly double ErrorWeight = -100.529;
/// <summary>
/// 是否允许接收数据
/// </summary>
protected bool IsAllowReceive { set; get; }
/// <summary>
/// 缓存
/// </summary>
protected ContentCache contentCache { set; get; } = ContentCache.CreateObj();
/// <summary>
/// 配置模型
/// </summary>
protected ConfigInfoModel configInfoModel = ConfigInfoModel.CreateObj();
/// <summary>
/// 消息显示委托
/// </summary>
public Action<string, bool, SysEnumInfon.MessageLogType> ShowMessageAction { set; get; }
/// <summary>
/// 判断的方法
/// </summary>
protected ElectronicScaleHandler.IElectronicBalanceHandler electronicBalanceHandler { set; get; }
/// <summary>
/// 是否使用模拟数据
/// </summary>
public bool IsUseSimulationData { protected set; get; }
/// <summary>
/// 当前字符解码方式
/// </summary>
public Encoding oneEncoding { set; get; } = Encoding.Default;
/// <summary>
///
/// </summary>
public virtual bool IsConnect { protected set; get; }
/// <summary>
/// 构建这个对象
/// </summary>
public abstract void Build(object config);
/// <summary>
/// 连接电子秤
/// </summary>
/// <returns></returns>
public abstract bool Connect();
/// <summary>
/// 断开电子秤
/// </summary>
/// <returns></returns>
public abstract bool UnConnect();
/// <summary>
/// 返回结果
/// </summary>
/// <returns></returns>
public abstract ElectronicBalanceResult ReadWeight();
/// <summary>
/// 可以传参数(标识电芯的信息)的获取重量结果
/// </summary>
/// <param name="keypar"></param>
/// <returns></returns>
public abstract ElectronicBalanceResult ReadWeight(string keypar);
public abstract void ReConnect();
}
}

View File

@@ -0,0 +1,149 @@
using HslCommunication.Core;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.PLC
{
/*
* plc的对象统一接口
* 描述了plc的连接 断开 读 写等操作
* by lzj
*/
public class DataResult
{
public bool IsSuccess { set; get; }
public string MessageInfo { set; get; }
}
public class DataResult<T> : DataResult
{
public T Data { set; get; }
}
public abstract class IPLCController
{
/// <summary>
/// plc的唯一标识
/// </summary>
public string KeyName { set; get; }
/// <summary>
/// 标签对应数据
/// </summary>
public ConcurrentDictionary<string, object> TagDic { set; get; } = new ConcurrentDictionary<string, object>();
/// <summary>
///
/// </summary>
public ConcurrentDictionary<object, object> ReadDataCache { protected set; get; } = new ConcurrentDictionary<object, object>();
/// <summary>
/// 规则字典
/// </summary>
public ConcurrentDictionary<string, PLCInteractionRuleModel> RuleDic { set; get; } = new ConcurrentDictionary<string, PLCInteractionRuleModel>();
/// <summary>
///
/// </summary>
public Encoding plcEncoding { protected set; get; }
/// <summary>
/// 数据转换
/// </summary>
public ByteTransformBase byteTransformBase { protected set; get; }
/// <summary>
/// 消息委托
/// </summary>
public Action<string, bool, Core.SysEnumInfon.MessageLogType> ShowMessageAction { set; get; }
/// <summary>
/// 是否连接
/// </summary>
public virtual bool IsConnect { protected set; get; }
/// <summary>
/// 是否有尝试连接了
/// </summary>
protected bool IsInit { set; get; }
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public abstract DataResult Connect(object config);
/// <summary>
/// 连接
/// </summary>
protected abstract void Connect();
/// <summary>
/// 断开
/// </summary>
/// <returns></returns>
public abstract DataResult UnConnect();
///// <summary>
///// 重连任务
///// </summary>
//protected Action ReConnectTask { set; get; }
/// <summary>
/// 读取
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
public abstract DataResult<T> ReadGenerics<T>(string address, ushort len);
/// <summary>
/// 读取
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
public abstract DataResult<byte[]> Read(string address, ushort len);
/// <summary>
/// 读取状态
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
public abstract DataResult<bool[]> ReadBools(string address, ushort len);
/// <summary>
/// 写入
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="address"></param>
/// <param name="data"></param>
/// <param name="len"></param>
/// <returns></returns>
public abstract DataResult Write<T>(string address, T data);
/// <summary>
/// 设置读写规则
/// </summary>
/// <param name="config"></param>
public abstract void SetRWRule(object config);
/// <summary>
/// 读取规则
/// </summary>
public abstract void ReadRule();
/// <summary>
/// 重连
/// </summary>
public virtual void ReConnect()
{
if (IsInit && !IsConnect)
{
Connect();
}
}
/// <summary>
/// 解析地址
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="firstaddress"></param>
/// <param name="arrdata"></param>
protected abstract void AnalysisArr<T>(string firstaddress, T[] arrdata);
public abstract T ReadDataFromDic<T>(string key);
public virtual T ReadOneTag<T>(string tag)
{
if (TagDic.ContainsKey(tag))
{
return (T)TagDic[tag];
}
return default(T);
}
}
}

View File

@@ -0,0 +1,949 @@
using Hsl=HslCommunication.Profinet.Keyence;
using StandardDomeNewApp.Core;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.PLC
{
public class PLC_KeyenceMcNet:IPLCController
{
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (value != base.IsConnect)
{
//前后两次不同
base.IsConnect = value;
if (Config == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TPlcConfigs.Where(o => o.FilterKey == Config.FilterKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 检测时间
/// </summary>
private DateTime checkTime { set; get; }
/// <summary>
/// 配置信息
/// </summary>
private PLCConfigModel Config { set; get; }
/// <summary>
/// plc对象
/// </summary>
private Hsl.KeyenceMcNet McNet;
/// <summary>
/// 连接PLC
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override DataResult Connect(object config)
{
if (config is PLCConfigModel model)
{
if (string.IsNullOrEmpty(model.EncodeName))
{
model.EncodeName = Encoding.Default.EncodingName;
plcEncoding = Encoding.GetEncoding(Encoding.Default.CodePage);
}
Config = model;
KeyName = Config.FilterKey;
if (McNet == null)
{
McNet = new Hsl.KeyenceMcNet(Config.IpAddress, Config.Port);
}
try
{
checkTime = DateTime.Now;
var result = McNet.ConnectServer();
if (result != null)
{
IsConnect = result.IsSuccess;
if (IsConnect == false)
{
Util.Log.Fatal("PLC_KeyenceMcNet"
, "Error 7:" + $"对象{Config.FilterKey}连接 {result.IsSuccess}详情:{result.Message}");
}
ShowMessageAction?.Invoke($"对象{Config.FilterKey}连接 {result.IsSuccess}详情:{result.Message}", false, SysEnumInfon.MessageLogType.Info);
return new DataResult
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message
};
}
}
catch (Exception ex)
{
IsConnect = false;
Util.Log.Fatal("PLC_KeyenceMcNet", "Error 0:" + ex.Message);
ShowMessageAction?.Invoke($"连接[{Config.FilterKey}]对象发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
finally
{
IsInit = true;
}
}
return null;
}
protected override void Connect()
{
Connect(Config);
}
/// <summary>
/// 读取二进制流
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
public override DataResult<byte[]> Read(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<byte[]>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = null
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<byte[]>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
try
{
var result = McNet.Read(address, len);
if (result != null)
{
IsConnect = result.IsSuccess;
return new DataResult<byte[]>
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message,
Data = result.Content
};
}
}
catch (Exception ex)
{
IsConnect = false;
Util.Log.Fatal("PLC_KeyenceMcNet", "Error 1:" + $"[{Config?.FilterKey}]对象读取byte数组发生异常详情{ex.Message}");
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取byte数组发生异常详情{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
/// <summary>
/// 读状态
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
public override DataResult<bool[]> ReadBools(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<bool[]>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = null
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<bool[]>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
try
{
var result = McNet.ReadBool(address, len);
if (result != null)
{
IsConnect = result.IsSuccess;
return new DataResult<bool[]>
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message,
Data = result.Content
};
}
}
catch (Exception ex)
{
IsConnect = false;
Util.Log.Fatal("PLC_KeyenceMcNet", "Error 2:" + $"[{Config?.FilterKey}]对象读取bool数组发生异常详情{ex.Message}");
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取bool数组发生异常详情{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
/// <summary>
/// 读取泛型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns>返回会有null的可能</returns>
public override DataResult<T> ReadGenerics<T>(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<T>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = default(T)
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<T>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
Type type = typeof(T);
DataResult<T> dataResult = null;
DataResult<object> resultdata = null;
try
{
if (type == typeof(short))
{
resultdata = new DataResult<object>();
var result = McNet.ReadInt16(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(ushort))
{
resultdata = new DataResult<object>();
var result = McNet.ReadUInt16(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(int))
{
resultdata = new DataResult<object>();
var result = McNet.ReadInt32(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(uint))
{
resultdata = new DataResult<object>();
var result = McNet.ReadUInt32(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(long))
{
resultdata = new DataResult<object>();
var result = McNet.ReadInt64(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(ulong))
{
resultdata = new DataResult<object>();
var result = McNet.ReadUInt64(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(float))
{
resultdata = new DataResult<object>();
var result = McNet.ReadFloat(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(double))
{
resultdata = new DataResult<object>();
var result = McNet.ReadDouble(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(bool))
{
resultdata = new DataResult<object>();
var result = McNet.ReadBool(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(short[]) || type == typeof(List<short>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadInt16(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(ushort[]) || type == typeof(List<ushort>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadUInt16(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(int[]) || type == typeof(List<int>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadInt32(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(uint[]) || type == typeof(List<uint>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadUInt32(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(long[]) || type == typeof(List<long>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadInt64(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(ulong[]) || type == typeof(List<ulong>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadUInt64(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(float[]) || type == typeof(List<float>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadFloat(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(double[]) || type == typeof(List<double>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadDouble(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(string))
{
//字符串
resultdata = new DataResult<object>();
var result = McNet.ReadString(address, len, Encoding.GetEncoding(Config.EncodeName));
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(byte[]) || type == typeof(List<byte>))
{
resultdata = new DataResult<object>();
var result = McNet.Read(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(bool[]) || type == typeof(List<bool>))
{
resultdata = new DataResult<object>();
var result = McNet.ReadBool(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
//此处如果有一种数据类型没有写在Cach里面PLC已经连接但是在此处置为false
//表现为PLC连接->断开->连接->连接……
else
{
resultdata = new DataResult<object>();
resultdata.IsSuccess = false;
resultdata.MessageInfo = "未知类型!无法获取数据!";
resultdata.Data = default(T);
}
}
catch (Exception ex)
{
IsConnect = false;
Util.Log.Fatal("PLC_KeyenceMcNet", "Error 4:"
+ $"[{Config?.FilterKey}]对象读取{type.Name}类型时发生异常!详情:{ex.Message}");
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取{type.Name}类型时发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
//数据转换
if (resultdata != null)
{
dataResult = new DataResult<T>
{
IsSuccess = resultdata.IsSuccess,
MessageInfo = resultdata.MessageInfo,
Data = (T)resultdata.Data
};
IsConnect = dataResult.IsSuccess;
}
return dataResult;
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public override DataResult UnConnect()
{
IsConnect = false;
IsInit = false;
try
{
var result = McNet?.ConnectClose();
McNet?.Dispose();
McNet = null;
if (result != null)
{
ShowMessageAction?.Invoke($"对象{Config.FilterKey}断开连接 {result.IsSuccess}详情:{result.Message}", false, SysEnumInfon.MessageLogType.Info);
return new DataResult
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message
};
}
}
catch (Exception ex)
{
Util.Log.Fatal("PLC_KeyenceMcNet", "Error 5:"
+ $"断开[{Config?.FilterKey}]连接对象发生异常!详情:{ex.Message}");
ShowMessageAction?.Invoke($"断开[{Config?.FilterKey}]连接对象发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override DataResult Write<T>(string address, T data)
{
if (!IsConnect)
{
return new DataResult
{
IsSuccess = false,
MessageInfo = "未连接PLC",
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult
{
IsSuccess = false,
MessageInfo = "该写入操作地址不能写入!"
};
}
Type type = typeof(T);
DataResult dataResult = null;
HslCommunication.OperateResult resultdata = null;
try
{
if (type == typeof(short))
{
if (data is short one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(ushort))
{
if (data is ushort one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(int))
{
if (data is int one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(uint))
{
if (data is uint one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(long))
{
if (data is long one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(ulong))
{
if (data is ulong one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(float))
{
if (data is float one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(double))
{
if (data is double one)
{
resultdata = McNet.Write(address, one);
}
}
else if (type == typeof(bool))
{
if (data is bool state)
{
resultdata = McNet.Write(address, state);
}
}
else if (type == typeof(short[]) || type == typeof(List<short>))
{
if (data is short[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<short> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(ushort[]) || type == typeof(List<ushort>))
{
if (data is ushort[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<ushort> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(int[]) || type == typeof(List<int>))
{
if (data is int[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<int> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(uint[]) || type == typeof(List<uint>))
{
if (data is uint[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<uint> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(long[]) || type == typeof(List<long>))
{
if (data is long[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<long> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(ulong[]) || type == typeof(List<ulong>))
{
if (data is ulong[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<ulong> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(float[]) || type == typeof(List<float>))
{
if (data is float[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<float> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(double[]) || type == typeof(List<double>))
{
if (data is double[] arr)
{
resultdata = McNet.Write(address, arr);
}
else if (data is List<double> list)
{
//list
resultdata = McNet.Write(address, list.ToArray());
}
}
else if (type == typeof(bool[]) || type == typeof(List<bool>))
{
if (data is bool[] arrb)
{
resultdata = McNet.Write(address, arrb);
}
else if (data is List<bool> listb)
{
resultdata = McNet.Write(address, listb.ToArray());
}
}
else if (type == typeof(string))
{
if (data is string str)
{
resultdata = McNet.Write(address, str, Encoding.GetEncoding(Config.EncodeName));
}
}
}
catch (Exception ex)
{
IsConnect = false;
Util.Log.Fatal("PLC_KeyenceMcNet", "Error 6:"
+ $"[{Config?.FilterKey}]对象写入{type.Name}类型{data.ToString()}数据时发生异常!详情:{ex.Message}");
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象写入{type.Name}类型{data.ToString()}数据时发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
if (resultdata != null)
{
dataResult = new DataResult
{
IsSuccess = resultdata.IsSuccess,
MessageInfo = resultdata.Message
};
IsConnect = dataResult.IsSuccess;
}
return dataResult;
}
private string GetownIp()
{
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
return AddressIP;
}
public override void SetRWRule(object config)
{
if (config is List<PLCInteractionRuleModel> ruleModels)
{
foreach (var ruleModel in ruleModels)
{
RuleDic[ruleModel.Address] = ruleModel;
}
}
}
public override void ReadRule()
{
if (RuleDic == null || RuleDic.Count < 1)
{
if ((DateTime.Now - checkTime).TotalSeconds > 20)
{
checkTime = DateTime.Now;
Connect();
}
//如果字典没有东西就返回
return;
}
checkTime = DateTime.Now;
foreach (var item in RuleDic)
{
var data = item.Value;
var plc_type = (SysEnumInfon.PLCDataType)Enum.Parse(typeof(SysEnumInfon.PLCDataType), data.DataType);
switch (plc_type)
{
case SysEnumInfon.PLCDataType.plc_short:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<short>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<short[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_ushort:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<ushort>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<ushort[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_int:
//if (data.Len < 2)
//{
// ReadDataCache[data] = ReadGenerics<int>(data.Address, (ushort)data.Len);
//}
//else
//{
// ReadDataCache[data] = ReadGenerics<int[]>(data.Address, (ushort)data.Len);
//}
//全部改为数组否则长度为1的时候不好判断,会导致出错
ReadDataCache[data] = ReadGenerics<int[]>(data.Address, (ushort)data.Len);
break;
case SysEnumInfon.PLCDataType.plc_uint:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<uint>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<uint[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_long:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<long>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<long[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_ulong:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<ulong>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<ulong[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_float:
//if (data.Len < 2)
//{
// ReadDataCache[data] = ReadGenerics<float>(data.Address, (ushort)data.Len);
//}
//else
//{
// ReadDataCache[data] = ReadGenerics<float[]>(data.Address, (ushort)data.Len);
//}
ReadDataCache[data] = ReadGenerics<float[]>(data.Address, (ushort)data.Len);
break;
case SysEnumInfon.PLCDataType.plc_double:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<double>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<double[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_bool:
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<bool>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<bool[]>(data.Address, (ushort)data.Len);
}
break;
case SysEnumInfon.PLCDataType.plc_string:
ReadDataCache[data] = ReadGenerics<string>(data.Address, (ushort)data.Len);
break;
default:
//字节
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<byte>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<byte[]>(data.Address, (ushort)data.Len);
}
break;
}
}
}
public override T ReadDataFromDic<T>(string key)
{
var model = ReadDataCache.FirstOrDefault(o => (o.Key as PLCInteractionRuleModel).Address == key);
if (model.Value != null)
{
if (model.Value is DataResult<T> data)
{
return data.Data;
}
return default(T);
}
return default(T);
}
protected override void AnalysisArr<T>(string firstaddress, T[] arrdata)
{
//throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,990 @@
using HslCommunication.Profinet.Melsec;
using StandardDomeNewApp.Core;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.PLC
{
public class PLC_MC3EBinary : IPLCController
{
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (value != base.IsConnect)
{
//前后两次不同
base.IsConnect = value;
if (Config == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_PlcConfigs.Where(o => o.FilterKey == Config.FilterKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 检测时间
/// </summary>
private DateTime checkTime { set; get; }
/// <summary>
/// 配置信息
/// </summary>
private PLCConfigModel Config { set; get; }
/// <summary>
/// MC协议对象
/// </summary>
private MelsecMcNet mcNet;
/// <summary>
/// 连接
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override DataResult Connect(object config)
{
if (config is PLCConfigModel model)
{
if (string.IsNullOrEmpty(model.EncodeName))
{
model.EncodeName = Encoding.Default.EncodingName;
plcEncoding = Encoding.GetEncoding(Encoding.Default.CodePage);
}
Config = model;
KeyName = Config.FilterKey;
if (mcNet == null)
{
mcNet = new MelsecMcNet(Config.IpAddress, Config.Port);
}
byteTransformBase = mcNet.ByteTransform;
try
{
checkTime = DateTime.Now;
var result = mcNet.ConnectServer();
if (result != null)
{
IsConnect = result.IsSuccess;
ShowMessageAction?.Invoke($"对象{Config.FilterKey}连接 {result.IsSuccess}详情:{result.Message}", false, SysEnumInfon.MessageLogType.Info);
return new DataResult
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message
};
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"连接[{Config.FilterKey}]对象发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
finally
{
IsInit = true;
}
}
return null;
}
/// <summary>
/// 读取
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
public override DataResult<byte[]> Read(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<byte[]>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = null
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<byte[]>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
try
{
var result = mcNet.Read(address, len);
if (result != null)
{
IsConnect = result.IsSuccess;
return new DataResult<byte[]>
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message,
Data = result.Content
};
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取byte数组发生异常详情{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override DataResult<bool[]> ReadBools(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<bool[]>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = null
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<bool[]>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
try
{
var result = mcNet.ReadBool(address, len);
if (result != null)
{
IsConnect = result.IsSuccess;
return new DataResult<bool[]>
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message,
Data = result.Content
};
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取bool数组发生异常详情{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override T ReadDataFromDic<T>(string key)
{
var model = ReadDataCache.FirstOrDefault(o => (o.Key as PLCInteractionRuleModel).Address == key);
if (model.Value != null)
{
if (model.Value is DataResult<T> data)
{
return data.Data;
}
return default(T);
}
return default(T);
}
public override DataResult<T> ReadGenerics<T>(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<T>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = default(T)
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<T>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
Type type = typeof(T);
DataResult<T> dataResult = null;
DataResult<object> resultdata = null;
try
{
if (type == typeof(short))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadInt16(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(ushort))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadUInt16(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(int))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadInt32(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(uint))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadUInt32(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(long))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadInt64(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(ulong))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadUInt64(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(float))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadFloat(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(double))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadDouble(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(bool))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadBool(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(short[]) || type == typeof(List<short>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadInt16(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(ushort[]) || type == typeof(List<ushort>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadUInt16(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(int[]) || type == typeof(List<int>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadInt32(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(uint[]) || type == typeof(List<uint>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadUInt32(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(long[]) || type == typeof(List<long>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadInt64(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(ulong[]) || type == typeof(List<ulong>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadUInt64(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(float[]) || type == typeof(List<float>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadFloat(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(double[]) || type == typeof(List<double>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadDouble(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(string))
{
//字符串
resultdata = new DataResult<object>();
var result = mcNet.ReadString(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(byte[]) || type == typeof(List<byte>))
{
resultdata = new DataResult<object>();
var result = mcNet.Read(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(bool[]) || type == typeof(List<bool>))
{
resultdata = new DataResult<object>();
var result = mcNet.ReadBool(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else
{
resultdata = new DataResult<object>();
resultdata.IsSuccess = false;
resultdata.MessageInfo = "未知类型!无法获取数据!";
resultdata.Data = default(T);
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取{type.Name}类型时发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
//数据转换
if (resultdata != null)
{
dataResult = new DataResult<T>
{
IsSuccess = resultdata.IsSuccess,
MessageInfo = resultdata.MessageInfo,
Data = (T)resultdata.Data
};
IsConnect = dataResult.IsSuccess;
}
return dataResult;
}
public override void ReadRule()
{
if (RuleDic == null || RuleDic.Count < 1)
{
if ((DateTime.Now - checkTime).TotalSeconds > 20)
{
checkTime = DateTime.Now;
Connect();
}
//如果字典没有东西就返回
return;
}
checkTime = DateTime.Now;
foreach (var item in RuleDic)
{
var data = item.Value;
var plc_type = (SysEnumInfon.PLCDataType)Enum.Parse(typeof(SysEnumInfon.PLCDataType), data.DataType);
switch (plc_type)
{
case SysEnumInfon.PLCDataType.plc_short:
if (data.Len < 2)
{
var one = ReadGenerics<short>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new short[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<short[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_ushort:
if (data.Len < 2)
{
var one = ReadGenerics<ushort>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new ushort[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<ushort[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_int:
if (data.Len < 2)
{
var one = ReadGenerics<int>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new int[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<int[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_uint:
if (data.Len < 2)
{
var one = ReadGenerics<uint>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new uint[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<uint[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_long:
if (data.Len < 2)
{
var one = ReadGenerics<long>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new long[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<long[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_ulong:
if (data.Len < 2)
{
var one = ReadGenerics<ulong>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new ulong[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<ulong[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_float:
if (data.Len < 2)
{
var one = ReadGenerics<float>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new float[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<float[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_double:
if (data.Len < 2)
{
var one = ReadGenerics<double>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new double[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<double[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_bool:
if (data.Len < 2)
{
var one = ReadGenerics<bool>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, new bool[] { one.Data });
ReadDataCache[data] = one;
}
else
{
var arr = ReadGenerics<bool[]>(data.Address, (ushort)data.Len);
AnalysisArr(data.Address, arr.Data);
ReadDataCache[data] = arr;
}
break;
case SysEnumInfon.PLCDataType.plc_string:
ReadDataCache[data] = ReadGenerics<string>(data.Address, (ushort)data.Len);
break;
default:
//字节
if (data.Len < 2)
{
ReadDataCache[data] = ReadGenerics<byte>(data.Address, (ushort)data.Len);
}
else
{
ReadDataCache[data] = ReadGenerics<byte[]>(data.Address, (ushort)data.Len);
}
break;
}
}
}
public override void SetRWRule(object config)
{
if (config is List<PLCInteractionRuleModel> ruleModels)
{
foreach (var ruleModel in ruleModels)
{
RuleDic[ruleModel.Address] = ruleModel;
}
}
}
public override DataResult UnConnect()
{
IsConnect = false;
IsInit = false;
try
{
var result = mcNet?.ConnectClose();
mcNet?.Dispose();
mcNet = null;
if (result != null)
{
ShowMessageAction?.Invoke($"对象{Config.FilterKey}断开连接 {result.IsSuccess}详情:{result.Message}", false, SysEnumInfon.MessageLogType.Info);
return new DataResult
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message
};
}
}
catch (Exception ex)
{
ShowMessageAction?.Invoke($"断开[{Config?.FilterKey}]连接对象发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override DataResult Write<T>(string address, T data)
{
if (!IsConnect)
{
return new DataResult
{
IsSuccess = false,
MessageInfo = "未连接PLC",
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult
{
IsSuccess = false,
MessageInfo = "该写入操作地址不能写入!"
};
}
Type type = typeof(T);
DataResult dataResult = null;
HslCommunication.OperateResult resultdata = null;
try
{
if (type == typeof(short))
{
if (data is short one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(ushort))
{
if (data is ushort one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(int))
{
if (data is int one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(uint))
{
if (data is uint one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(long))
{
if (data is long one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(ulong))
{
if (data is ulong one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(float))
{
if (data is float one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(double))
{
if (data is double one)
{
resultdata = mcNet.Write(address, one);
}
}
else if (type == typeof(bool))
{
if (data is bool state)
{
resultdata = mcNet.Write(address, state);
}
}
else if (type == typeof(short[]) || type == typeof(List<short>))
{
if (data is short[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<short> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(ushort[]) || type == typeof(List<ushort>))
{
if (data is ushort[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<ushort> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(int[]) || type == typeof(List<int>))
{
if (data is int[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<int> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(uint[]) || type == typeof(List<uint>))
{
if (data is uint[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<uint> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(long[]) || type == typeof(List<long>))
{
if (data is long[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<long> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(ulong[]) || type == typeof(List<ulong>))
{
if (data is ulong[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<ulong> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(float[]) || type == typeof(List<float>))
{
if (data is float[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<float> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(double[]) || type == typeof(List<double>))
{
if (data is double[] arr)
{
resultdata = mcNet.Write(address, arr);
}
else if (data is List<double> list)
{
//list
resultdata = mcNet.Write(address, list.ToArray());
}
}
else if (type == typeof(bool[]) || type == typeof(List<bool>))
{
if (data is bool[] arrb)
{
resultdata = mcNet.Write(address, arrb);
}
else if (data is List<bool> listb)
{
resultdata = mcNet.Write(address, listb.ToArray());
}
}
else if (type == typeof(string))
{
if (data is string str)
{
resultdata = mcNet.Write(address, str);
}
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象写入{type.Name}类型{data.ToString()}数据时发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
if (resultdata != null)
{
dataResult = new DataResult
{
IsSuccess = resultdata.IsSuccess,
MessageInfo = resultdata.Message
};
IsConnect = dataResult.IsSuccess;
}
return dataResult;
}
protected override void AnalysisArr<T>(string firstaddress, T[] arrdata)
{
if (string.IsNullOrEmpty(firstaddress))
{
return;
}
firstaddress = firstaddress.ToUpper();
if (arrdata.Length > 1)
{
if (typeof(bool) == typeof(T))
{
//状态、报警的
if (firstaddress.Contains("X") || firstaddress.Contains("Y") || firstaddress.Contains("B") || firstaddress.Contains("M") || firstaddress.Contains("L"))
{
var addresstype = firstaddress.Substring(0, 1);
var addressnum = firstaddress.Replace("X", "").Replace("Y", "").Replace("B", "").Replace("M", "").Replace("L", "");
var arr = addressnum.Split('.');
int realnum;
int decimalnum = 0;
if (arr.Length == 1)
{
realnum = int.Parse(arr[0]);
}
else
{
realnum = int.Parse(arr[0]);
decimalnum = int.Parse(arr[1]);
}
for (int i = 0; i < arrdata.Length; i++)
{
var real = i / 16;
var deci = i % 16;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(addresstype);
stringBuilder.Append((realnum + real).ToString());
stringBuilder.Append(".");
stringBuilder.Append((decimalnum + deci).ToString());
//var address = addresstype + (realnum + real).ToString() + "." + (decimalnum + deci).ToString();
TagDic[stringBuilder.ToString()] = arrdata[i];
}
}
}
else
{
//数据的
if (firstaddress.Contains("D") || firstaddress.Contains("R"))
{
var addresstype = firstaddress.Substring(0, 1);
var addressnum = firstaddress.Replace("D", "").Replace("R", "");
int numaddress = int.Parse(addressnum);
for (int i = 0; i < arrdata.Length; i++)
{
var address = addresstype + (numaddress + i).ToString();
TagDic[address] = arrdata[i];
}
}
}
}
else
{
TagDic[firstaddress] = arrdata[0];
}
}
protected override void Connect()
{
Connect(Config);
}
}
}

View File

@@ -0,0 +1,939 @@
using HslCommunication.Core;
using HslCommunication.Profinet.Omron;
using StandardDomeNewApp.Core;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.PLC
{
public class PLC_OmronCIP : IPLCController
{
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (value != base.IsConnect)
{
//前后两次不同
base.IsConnect = value;
if (Config == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TPlcConfigs.Where(o => o.FilterKey == Config.FilterKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 检测时间
/// </summary>
private DateTime checkTime { set; get; }
/// <summary>
/// 配置信息
/// </summary>
private PLCConfigModel Config { set; get; }
/// <summary>
/// cip plc对象
/// </summary>
private OmronCipNet omronCipNet { set; get; }
/// <summary>
/// 连接
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override DataResult Connect(object config)
{
if (config is PLCConfigModel model)
{
if (string.IsNullOrEmpty(model.EncodeName))
{
model.EncodeName = Encoding.Default.EncodingName;
plcEncoding = Encoding.GetEncoding(Encoding.Default.CodePage);
}
Config = model;
KeyName = Config.FilterKey;
if (omronCipNet == null)
{
omronCipNet = new OmronCipNet(Config.IpAddress, Config.Port)
{
Slot = Config.Slot
};
}
switch (Config.ByteDataFormat)
{
case 0x00:
omronCipNet.ByteTransform.DataFormat = DataFormat.ABCD;
break;
case 0x01:
omronCipNet.ByteTransform.DataFormat = DataFormat.BADC;
break;
case 0x02:
omronCipNet.ByteTransform.DataFormat = DataFormat.CDAB;
break;
case 0x03:
omronCipNet.ByteTransform.DataFormat = DataFormat.DCBA;
break;
}
byteTransformBase = omronCipNet.ByteTransform;
try
{
checkTime = DateTime.Now;
var result = omronCipNet.ConnectServer();
if (result != null)
{
IsConnect = result.IsSuccess;
ShowMessageAction?.Invoke($"对象{Config.FilterKey}连接 {result.IsSuccess}详情:{result.Message}", false, SysEnumInfon.MessageLogType.Info);
return new DataResult
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message
};
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"连接[{Config.FilterKey}]对象发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
finally
{
IsInit = true;
}
}
return null;
}
protected override void Connect()
{
Connect(Config);
}
public override DataResult<byte[]> Read(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<byte[]>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = null
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<byte[]>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
try
{
var result = omronCipNet.Read(address, len);
if (result != null)
{
IsConnect = result.IsSuccess;
return new DataResult<byte[]>
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message,
Data = result.Content
};
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取byte数组发生异常详情{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override DataResult<bool[]> ReadBools(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<bool[]>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = null
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<bool[]>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
try
{
var result = omronCipNet.ReadBool(address, len);
if (result != null)
{
IsConnect = result.IsSuccess;
return new DataResult<bool[]>
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message,
Data = result.Content
};
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取bool数组发生异常详情{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override DataResult<T> ReadGenerics<T>(string address, ushort len)
{
if (!IsConnect)
{
return new DataResult<T>
{
IsSuccess = false,
MessageInfo = "未连接PLC",
Data = default(T)
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult<T>
{
IsSuccess = false,
MessageInfo = "该读取操作地址只能写入,无法读取"
};
}
Type type = typeof(T);
DataResult<T> dataResult = null;
DataResult<object> resultdata = null;
try
{
if (type == typeof(short))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadInt16(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(ushort))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadUInt16(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(int))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadInt32(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(uint))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadUInt32(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(long))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadInt64(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(ulong))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadUInt64(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(float))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadFloat(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(double))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadDouble(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(bool))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadBool(address);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
resultdata.Data = result.Content;
}
else if (type == typeof(short[]) || type == typeof(List<short>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadInt16(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(ushort[]) || type == typeof(List<ushort>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadUInt16(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(int[]) || type == typeof(List<int>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadInt32(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(uint[]) || type == typeof(List<uint>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadUInt32(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(long[]) || type == typeof(List<long>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadInt64(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(ulong[]) || type == typeof(List<ulong>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadUInt64(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(float[]) || type == typeof(List<float>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadFloat(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(double[]) || type == typeof(List<double>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadDouble(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(string))
{
//字符串
resultdata = new DataResult<object>();
var result = omronCipNet.ReadString(address, len, Encoding.GetEncoding(Config.EncodeName));
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(byte[]) || type == typeof(List<byte>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.Read(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else if (type == typeof(bool[]) || type == typeof(List<bool>))
{
resultdata = new DataResult<object>();
var result = omronCipNet.ReadBool(address, len);
resultdata.IsSuccess = result.IsSuccess;
resultdata.MessageInfo = result.Message;
if (CommonlyJudge.IsIsList(type))
{
resultdata.Data = result.Content.ToList();
}
else
{
resultdata.Data = result.Content;
}
}
else
{
resultdata = new DataResult<object>();
resultdata.IsSuccess = false;
resultdata.MessageInfo = "未知类型!无法获取数据!";
resultdata.Data = default(T);
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象读取{type.Name}类型时发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
//数据转换
if (resultdata != null)
{
dataResult = new DataResult<T>
{
IsSuccess = resultdata.IsSuccess,
MessageInfo = resultdata.MessageInfo,
Data = (T)resultdata.Data
};
IsConnect = dataResult.IsSuccess;
}
return dataResult;
}
/// <summary>
/// cip里的读取规则按照一个个标签读取
/// </summary>
public override void ReadRule()
{
if (RuleDic == null || RuleDic.Count < 1)
{
if ((DateTime.Now - checkTime).TotalSeconds > 20)
{
checkTime = DateTime.Now;
Connect();
}
//如果字典没有东西就返回
return;
}
checkTime = DateTime.Now;
//非bool的标签
List<CIPTag> CipTags = new List<CIPTag>();
//整理出bool的标签和非bool
foreach (var item in RuleDic)
{
var data = item.Value;
var plc_type = (SysEnumInfon.PLCDataType)Enum.Parse(typeof(SysEnumInfon.PLCDataType), data.DataType);
if (plc_type == SysEnumInfon.PLCDataType.plc_bool || plc_type == SysEnumInfon.PLCDataType.plc_string)
{
if (plc_type == SysEnumInfon.PLCDataType.plc_bool)
{
//读取bool
var one = ReadBools(data.Address, 1);
ReadDataCache[data] = one;
AnalysisArr(data.Address, one.Data);
}
else
{
var one = ReadGenerics<string>(data.Address, (ushort)data.Len);
ReadDataCache[data] = one;
AnalysisArr(data.Address, new string[] { one.Data });
}
continue;
}
var tag = new CIPTag
{
Tag = data.Address,
DataType = plc_type
};
switch (plc_type)
{
case SysEnumInfon.PLCDataType.plc_short:
tag.Len = 2;
break;
case SysEnumInfon.PLCDataType.plc_ushort:
tag.Len = 2;
break;
case SysEnumInfon.PLCDataType.plc_int:
tag.Len = 4;
break;
case SysEnumInfon.PLCDataType.plc_uint:
tag.Len = 4;
break;
case SysEnumInfon.PLCDataType.plc_long:
tag.Len = 8;
break;
case SysEnumInfon.PLCDataType.plc_ulong:
tag.Len = 8;
break;
case SysEnumInfon.PLCDataType.plc_float:
tag.Len = 4;
break;
case SysEnumInfon.PLCDataType.plc_double:
tag.Len = 8;
break;
default:
break;
}
CipTags.Add(tag);
}
var tags = CipTags.Select(p => p.Tag).ToArray();
var resultbytes = omronCipNet.Read(tags);
var bytes = resultbytes.Content.ToList();
//解析cip标签
int len = 0;
for (int i = 0; i < CipTags.Count; i++)
{
CipTags[i].Datas = bytes.Skip(len).Take(CipTags[i].Len).ToArray();
len += CipTags[i].Len;
switch (CipTags[i].DataType)
{
case SysEnumInfon.PLCDataType.plc_short:
var shortdata = byteTransformBase.TransInt16(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new short[] { shortdata });
break;
case SysEnumInfon.PLCDataType.plc_ushort:
var ushortdata = byteTransformBase.TransUInt16(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new ushort[] { ushortdata });
break;
case SysEnumInfon.PLCDataType.plc_int:
var intdata = byteTransformBase.TransInt32(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new int[] { intdata });
break;
case SysEnumInfon.PLCDataType.plc_uint:
var uintdata = byteTransformBase.TransUInt32(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new uint[] { uintdata });
break;
case SysEnumInfon.PLCDataType.plc_long:
var longdata = byteTransformBase.TransInt64(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new long[] { longdata });
break;
case SysEnumInfon.PLCDataType.plc_ulong:
var ulongdata = byteTransformBase.TransUInt64(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new ulong[] { ulongdata });
break;
case SysEnumInfon.PLCDataType.plc_float:
var fdata = byteTransformBase.TransSingle(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new float[] { fdata });
break;
case SysEnumInfon.PLCDataType.plc_double:
var ddata = byteTransformBase.TransDouble(CipTags[i].Datas, 0);
AnalysisArr(CipTags[i].Tag, new double[] { ddata });
break;
default:
break;
}
}
}
public override void SetRWRule(object config)
{
if (config is List<PLCInteractionRuleModel> ruleModels)
{
foreach (var ruleModel in ruleModels)
{
RuleDic[ruleModel.Address] = ruleModel;
}
}
}
public override DataResult UnConnect()
{
IsConnect = false;
IsInit = false;
try
{
var result = omronCipNet?.ConnectClose();
omronCipNet?.Dispose();
omronCipNet = null;
if (result != null)
{
ShowMessageAction?.Invoke($"对象{Config.FilterKey}断开连接 {result.IsSuccess}详情:{result.Message}", false, SysEnumInfon.MessageLogType.Info);
return new DataResult
{
IsSuccess = result.IsSuccess,
MessageInfo = result.Message
};
}
}
catch (Exception ex)
{
ShowMessageAction?.Invoke($"断开[{Config?.FilterKey}]连接对象发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
return null;
}
public override DataResult Write<T>(string address, T data)
{
if (!IsConnect)
{
return new DataResult
{
IsSuccess = false,
MessageInfo = "未连接PLC",
};
}
if (RuleDic != null && RuleDic.ContainsKey(address) && RuleDic[address].OpType == SysEnumInfon.PLCOperationType..ToString())
{
return new DataResult
{
IsSuccess = false,
MessageInfo = "该写入操作地址不能写入!"
};
}
Type type = typeof(T);
DataResult dataResult = null;
HslCommunication.OperateResult resultdata = null;
try
{
if (type == typeof(short))
{
if (data is short one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(ushort))
{
if (data is ushort one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(int))
{
if (data is int one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(uint))
{
if (data is uint one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(long))
{
if (data is long one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(ulong))
{
if (data is ulong one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(float))
{
if (data is float one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(double))
{
if (data is double one)
{
resultdata = omronCipNet.Write(address, one);
}
}
else if (type == typeof(bool))
{
if (data is bool state)
{
resultdata = omronCipNet.Write(address, state);
}
}
else if (type == typeof(short[]) || type == typeof(List<short>))
{
if (data is short[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<short> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(ushort[]) || type == typeof(List<ushort>))
{
if (data is ushort[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<ushort> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(int[]) || type == typeof(List<int>))
{
if (data is int[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<int> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(uint[]) || type == typeof(List<uint>))
{
if (data is uint[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<uint> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(long[]) || type == typeof(List<long>))
{
if (data is long[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<long> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(ulong[]) || type == typeof(List<ulong>))
{
if (data is ulong[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<ulong> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(float[]) || type == typeof(List<float>))
{
if (data is float[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<float> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(double[]) || type == typeof(List<double>))
{
if (data is double[] arr)
{
resultdata = omronCipNet.Write(address, arr);
}
else if (data is List<double> list)
{
//list
resultdata = omronCipNet.Write(address, list.ToArray());
}
}
else if (type == typeof(bool[]) || type == typeof(List<bool>))
{
if (data is bool[] arrb)
{
resultdata = omronCipNet.Write(address, arrb);
}
else if (data is List<bool> listb)
{
resultdata = omronCipNet.Write(address, listb.ToArray());
}
}
else if (type == typeof(string))
{
if (data is string str)
{
resultdata = omronCipNet.Write(address, str, Encoding.GetEncoding(Config.EncodeName));
}
}
}
catch (Exception ex)
{
IsConnect = false;
ShowMessageAction?.Invoke($"[{Config?.FilterKey}]对象写入{type.Name}类型{data.ToString()}数据时发生异常!详情:{ex.Message}",
false, SysEnumInfon.MessageLogType.Error);
}
if (resultdata != null)
{
dataResult = new DataResult
{
IsSuccess = resultdata.IsSuccess,
MessageInfo = resultdata.Message
};
IsConnect = dataResult.IsSuccess;
}
return dataResult;
}
public override T ReadDataFromDic<T>(string key)
{
var model = ReadDataCache.FirstOrDefault(o => (o.Key as PLCInteractionRuleModel).Address == key);
if (model.Value != null)
{
if (model.Value is DataResult<T> data)
{
return data.Data;
}
return default(T);
}
return default(T);
}
protected override void AnalysisArr<T>(string firstaddress, T[] arrdata)
{
if (string.IsNullOrEmpty(firstaddress))
{
return;
}
firstaddress = firstaddress.ToUpper();
if (arrdata.Length > 1)
{
//cip不处理
}
else
{
TagDic[firstaddress] = arrdata[0];
}
}
}
public class CIPTag
{
/// <summary>
/// 标签名称
/// </summary>
public string Tag { set; get; }
/// <summary>
/// 标签值
/// </summary>
public byte[] Datas { set; get; }
/// <summary>
/// 占用多少字节
/// </summary>
public int Len { set; get; }
/// <summary>
/// 当前标签类型
/// </summary>
public SysEnumInfon.PLCDataType DataType { set; get; }
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
using libplctag;
using libplctag.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Model.Communication
{
public class UShortCipPlcMapper : PlcMapperBase<ushort>
{
public override int? ElementSize => 2;
public override ushort Decode(Tag tag, int offset)
{
return tag.GetUInt16(offset);
}
public override void Encode(Tag tag, int offset, ushort value)
{
tag.SetUInt16(offset, value);
}
}
public class UIntCipPlcMapper : PlcMapperBase<uint>
{
public override int? ElementSize => 4;
public override uint Decode(Tag tag, int offset)
{
return tag.GetUInt32(offset);
}
public override void Encode(Tag tag, int offset, uint value)
{
tag.SetUInt32(offset, value);
}
}
public class ULongCipPlcMapper : PlcMapperBase<ulong>
{
public override int? ElementSize => 8;
public override ulong Decode(Tag tag, int offset)
{
return tag.GetUInt64(offset);
}
public override void Encode(Tag tag, int offset, ulong value)
{
tag.SetUInt64(offset, value);
}
}
public class Short5
{
public short[] Data { set; get; } = new short[5];
}
public class Short5CipPlcMapper : PlcMapperBase<Short5>
{
public override int? ElementSize => 10;
public override Short5 Decode(Tag tag, int offset)
{
Short5 short5 = new Short5();
for (int i = 0; i < short5.Data.Length; i++)
{
short5.Data[i] = tag.GetInt16(offset + i * 2);
}
return short5;
}
public override void Encode(Tag tag, int offset, Short5 value)
{
for (int i = 0; i < value.Data.Length; i++)
{
tag.SetInt16(offset + i * 2, value.Data[i]);
}
}
}
}

View File

@@ -0,0 +1,40 @@
using KoboldCom;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SerialPorts
{
/// <summary>
/// 交互协议的集合
/// by lzj
/// </summary>
public class InteractionProtocols : IAnalyzerCollection
{
public InteractionProtocols()
{
_innerArray = new List<IAnalyzer>();
}
private readonly List<IAnalyzer> _innerArray;
public IAnalyzer this[int index]
{
get
{
return _innerArray[index];
}
}
public IEnumerator<IAnalyzer> GetEnumerator()
{
return ((IEnumerable<IAnalyzer>)_innerArray).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _innerArray.GetEnumerator();
}
}
}

View File

@@ -0,0 +1,214 @@
using KoboldCom;
using StandardDomeNewApp.Core;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SerialPorts
{
/// <summary>
/// 串口的控制器模块 这个模块是负责串口的通讯+通讯交互协议的解析
/// by lzj
/// </summary>
public class SeriaPortController
{
private Communicator communicator { set; get; }
/// <summary>
/// 本机上现有的端口
/// </summary>
public List<string> PortNames
{
get => GetPortNames();
}
/// <summary>
/// 返回波特率
/// </summary>
public List<int> Baudrates
{
get => GetBaudrates();
}
/// <summary>
/// 写死的波特率
/// </summary>
private List<int> baudRayes = new List<int>
{
600,1200,2400,4800,9600,14400,19200,38400,56000,57600,115200
};
/// <summary>
///
/// </summary>
private SerialPortConfigModel serialPortConfigModel { set; get; }
/// <summary>
/// 是否串口打开
/// </summary>
public bool IsOpen { private set; get; }
/// <summary>
/// 编码方式
/// </summary>
public Encoding encoding { set; get; }
/// <summary>
/// 获取原始数据的委托
/// </summary>
public Action<byte[], Encoding> RawDataAction { set; get; }
/// <summary>
/// 消息委托
/// </summary>
public Action<string, bool, SysEnumInfon.MessageLogType> ShowMessageAction { set; get; }
private bool IsInitComplete { set; get; }
/// <summary>
/// 串口的控制器模块 这个模块是负责串口的通讯+通讯交互协议的解析
/// </summary>
public SeriaPortController(object config)
{
GetPortNames();
if (config is SerialPortConfigModel serial)
{
serialPortConfigModel = serial;
//实例化
communicator = new Communicator(new SerialPort(), new InteractionProtocols());
//编码方式
communicator.Com.Encoding = encoding = Encoding.GetEncoding(serialPortConfigModel.EncodeName);
//注册InteractionProtocols特定协议的事件
if (communicator.Analyzers is InteractionProtocols analyzers)
{
//处理InteractionProtocols里的返回事件
}
//原始数据返回的事件
communicator.OnRawDataReceived += Communicator_OnRawDataReceived;
}
}
/// <summary>
/// 串口获取串口名称
/// </summary>
/// <returns></returns>
public List<string> GetPortNames()
{
var ports = System.IO.Ports.SerialPort.GetPortNames();
if (ports == null)
{
return null;
}
return ports.ToList(); ;
}
/// <summary>
/// 返回波特率
/// </summary>
/// <returns></returns>
public List<int> GetBaudrates()
{
return baudRayes;
}
/// <summary>
/// 打开串口
/// </summary>
public bool Open()
{
if (serialPortConfigModel != null)
{
SerialPortSetting sps = new SerialPortSetting
{
Baudrate = serialPortConfigModel.Baudrate,
NewLine = Environment.NewLine,
Handshake = SysEnumHelp.GetHandshake(serialPortConfigModel.Handshake),
Parity = SysEnumHelp.GetParity(serialPortConfigModel.Parity),
Port = int.Parse(System.Text.RegularExpressions.Regex.Match(serialPortConfigModel.Port, @"\d+").Value),
StopBits = SysEnumHelp.GetStopBits(serialPortConfigModel.StopBits)
};
try
{
IsOpen = communicator.Com.Open(sps);
}
catch (Exception ex)
{
ShowMessageAction?.Invoke($"打开对象{serialPortConfigModel.FilterKey}串口发生异常!详情:{ex.Message}", false, SysEnumInfon.MessageLogType.Warn);
}
ShowMessageAction?.Invoke($"对象{serialPortConfigModel.FilterKey}串口打开 {IsOpen}", false, SysEnumInfon.MessageLogType.Info);
IsInitComplete = true;
return IsOpen;
}
return false;
}
/// <summary>
/// 关闭串口
/// </summary>
public void Close()
{
if (IsOpen)
{
try
{
communicator.Com.Close();
}
catch (Exception ex)
{
ShowMessageAction?.Invoke($"关闭对象{serialPortConfigModel.FilterKey}串口发生异常!详情:{ex.Message}", false, SysEnumInfon.MessageLogType.Warn);
}
IsOpen = false;
ShowMessageAction?.Invoke($"对象{serialPortConfigModel.FilterKey}串口关闭", false, SysEnumInfon.MessageLogType.Info);
}
else
{
ShowMessageAction?.Invoke($"对象{serialPortConfigModel.FilterKey}串口未开启,无需关闭!", false, SysEnumInfon.MessageLogType.Warn);
}
IsInitComplete = false;
}
/// <summary>
/// 发送
/// </summary>
/// <param name="text"></param>
public void Send(string text)
{
if (IsOpen)
{
communicator.Com.Write(text);
}
else
{
ShowMessageAction?.Invoke($"对象{serialPortConfigModel.FilterKey}串口未开启,无法发送!", false, SysEnumInfon.MessageLogType.Warn);
}
}
/// <summary>
/// 发送
/// </summary>
/// <param name="datas"></param>
public void Send(byte[] datas)
{
if (IsOpen)
{
communicator.Com.Write(encoding.GetString(datas));
}
else
{
ShowMessageAction?.Invoke($"对象{serialPortConfigModel.FilterKey}串口未开启,无法发送!", false, SysEnumInfon.MessageLogType.Warn);
}
}
#region
/// <summary>
/// 原生数据
/// </summary>
/// <param name="bytes"></param>
private void Communicator_OnRawDataReceived(byte[] bytes)
{
RawDataAction?.Invoke(bytes, encoding);
}
#endregion
public void ReTryOpen()
{
if (IsInitComplete && !IsOpen)
{
Open();
}
}
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SignalRClient.ClinetMethods
{
/// <summary>
/// 举个例子 这个是方法在中间件集线器上的那个接口 这个里面的方法都要是无返回值的
/// </summary>
public interface IClientMethods
{
void ClientReceive(Model.WeiHongModel.WeiHongReturnModel.MESFeedback MESFeedback);
}
}

View File

@@ -0,0 +1,21 @@
using StandardDomeNewApp.Core;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SignalRClient.ClinetMethods
{
public class TestClientMethod : IClientMethods
{
public ConcurrentDictionary<string, Func<object>> ConnectingDeviceDic { set; get; }
= new ConcurrentDictionary<string, Func<object>>();
public void ClientReceive(Model.WeiHongModel.WeiHongReturnModel.MESFeedback MESFeedback)
{
}
}
}

View File

@@ -0,0 +1,307 @@
using Microsoft.AspNet.SignalR.Client;
using StandardDomeNewApp.Communication.SignalRClient.ClinetMethods;
using StandardDomeNewApp.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StandardDomeNewApp.Model.WeiHongModel;
using StandardDomeNewApp.Model;
using Newtonsoft.Json;
using static StandardDomeNewApp.Model.WeiHongModel.WeiHongReturnModel;
using static StandardDomeNewApp.Model.MESDataModel;
using static StandardDomeNewApp.Model.GuanYu.GYInterfaceModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace StandardDomeNewApp.Communication.SignalRClient.HubMethods
{
public class HubClient : IHubClient
{
private ConfigInfoModel configInfoModel { set; get; } = ConfigInfoModel.CreateObj();
#region
/// <summary>
///
/// </summary>
private IClientMethods clientMethods { set; get; }
public FrameworkElement framework { set; get; }
#endregion
private ContentCache contentCache = ContentCache.CreateObj(); //用于读取PLC数据
public override void Init(IHubProxy hubProxy)
{
proxy = hubProxy;
//这种类都是后续按照这个格式添加 这里是客户端的方法实例化 如果不同的类型就用不同接口实现不同方法
//clientMethods = new TestClientMethod();
}
public override void BeginRegister()
{
if (proxy == null)
{
return;
}
if (clientMethods == null)
{
return;
}
//proxy.On<WeiHongReturnModel.MESFeedback>("ClientReceive", (MESFeedback) =>
//{
// clientMethods.ClientReceive(MESFeedback);
//});
}
public void SignalServerInvoke(int CMD,string JSONPara)
{
if (View.MainWindow.isUploadMES==false)
{
return;
}
switch (CMD)
{
case 0:
Test(JSONPara);
break;
case (int)Model.MESDataModel.CMDType.:
var mesFeedBack= GetProjCode(JSONPara);
break;
case (int)Model.MESDataModel.CMDType.:
GetWaterResult(JSONPara);
break;
case (int)Model.MESDataModel.CMDType.:
var checkCell= CheckCell(JSONPara,"");
break;
case (int)Model.MESDataModel.CMDType.:
GetWaterResult(JSONPara);
break;
case (int)Model.MESDataModel.CMDType.:
GetWaterResult(JSONPara);
break;
}
}
private async Task Test(string JSONPara)
{
Model.MESDataModel.SendHeaderWithDtl sendHeaderWithDtl = new SendHeaderWithDtl();
sendHeaderWithDtl.Cmd = 1;
Model.MESDataModel.SendListItem sendListItem = new SendListItem();
sendListItem.DataPreporty = "TestName";
sendListItem.DataValue = JSONPara;
object MESFeedBack = await Send(sendHeaderWithDtl);
}
/// <summary>
/// 获取产品型号
/// </summary>
/// <param name="jsonPara"></param>
/// <returns></returns>
public async Task<Model.GuanYu.GYInterfaceModel.RtnZHComm> GetProjCode(string machineNo)
{
Model.MESDataModel.SendHeaderWithDtl sendHeaderWithDtl = new SendHeaderWithDtl();
sendHeaderWithDtl.Cmd = (int)Model.MESDataModel.CMDType.;
string computerName = System.Environment.MachineName;
List<Model.MESDataModel.SendListItem> sendListItems = new List<Model.MESDataModel.SendListItem>
{
new SendListItem{ DataPreporty="MachineNo",DataValue=machineNo },
new SendListItem{ DataPreporty="ProcName",DataValue="HK" },
new SendListItem{ DataPreporty="GXDM",DataValue="002" },
new SendListItem{ DataPreporty="ComputerName",DataValue=computerName }
};
sendHeaderWithDtl.DataList = sendListItems;
MESFeedback mesFeedBack = await Send(sendHeaderWithDtl);
string result = mesFeedBack.MesResult.ToString();
Model.GuanYu.GYInterfaceModel.RtnZHComm rt = JsonConvert.DeserializeObject<Model.GuanYu.GYInterfaceModel.RtnZHComm>(result);
string value = rt.code;
string value2 = rt.msg;
List<string> valueList = rt.ProjCode;
return rt;
}
/// <summary>
/// 校验电芯
/// </summary>
/// <param name="jsonPara"></param>
/// <returns></returns>
public async Task<string> CheckCell(string code,string projCode)
{
Model.MESDataModel.SendHeaderWithDtl sendHeaderWithDtl = new SendHeaderWithDtl();
sendHeaderWithDtl.Cmd = 2; //(int)Model.MESDataModel.CMDType.电芯条码校验;
string computerName = System.Environment.MachineName;
List<Model.MESDataModel.SendListItem> sendListItems = new List<Model.MESDataModel.SendListItem>
{
new SendListItem{ DataPreporty="CellName",DataValue=code },//电芯条码
new SendListItem{ DataPreporty="ProjCode",DataValue=projCode },//电芯型号
new SendListItem{ DataPreporty="infoData1",DataValue="0" },//周次樊工说不用传。3C才需要
new SendListItem{ DataPreporty="ComputerName",DataValue=computerName }//计算机名
};
sendHeaderWithDtl.DataList = sendListItems;
MESFeedback mesFeedBack = await Send(sendHeaderWithDtl);
string result = mesFeedBack.MesResult.ToString();
Model.GuanYu.GYInterfaceModel.RtnZHComm rt = JsonConvert.DeserializeObject<Model.GuanYu.GYInterfaceModel.RtnZHComm>(result);
string successfulCode = rt.code;
string msg = rt.msg;
if(successfulCode=="0")
{
msg = "true";
}
return msg;
}
/// <summary>
/// 烘烤数据上传
/// </summary>
/// <param name="code"></param>
/// <param name="projCode"></param>
/// <returns></returns>
private async Task UploadBakeData(string code, string projCode)
{
#region
string sql = $@" select a.BatteryCode as Cell_Name,
a.ProjectCode as Proj_Code ,
case when b.WaterResult='OK' then '0'else '1'end as Quality,
'' as NGReason ,
a.CreateTime as StartDate,
b.BeginBakeTime as Baking_Start_Time,
b.EndBakeTime as Baking_End_Time,
'' as Distribution_Num,
c.CavityNo as Cavity ,
b.Layer as Lay ,
'' as Position,
'' as Vacuum_Chamber,
f.Value as Valve_Vacuum,#真空值
e.Value as Temperature,#温度平均值
'machine' as Machine_No,#设备编号
a.UserId as Operator,#操作工
d.WaterContent as Water_Content,# 水含量
a.IsSample as IsTestSample,
'' as Remark ,
'' as Extensions_1,
'' as Extensions_2,
b.BeginBakeAgainTime as Bakeagain_Start_Time,
b.EndBakeAgainTime as Bakeagain_End_Time,
e.AgainValue as Bakeagain_Temperature ,#加烘温度
f.AgainValue as Bakeagain_Vacuum #真空
,b.CurrentId
from TPalletCode a
left join TPallet b on a.PalletCode =b.PalletCode
left join TMachineState c on b.PalletCode =c.PalletCode
left join TWaterSample d on a.BatteryCode =d.BatteryCode
left join TStatusHistoryDataAVG e on b.CurrentId =e.CurrentId and e.DataType ='Temperature'
left join TStatusHistoryDataAVG f on b.CurrentId =f.CurrentId and f.DataType ='Vacuum'
where a.BatteryCode ='{code}' ";
#endregion
DataTable Dt = Util.DatabaseHelper.GetDataTable(sql);
Model.MESDataModel.SendHeaderWithDtl sendHeaderWithDtl = new SendHeaderWithDtl();
Model.MESDataModel.SendHeaderWithDtl MESDataModel =
new Model.MESDataModel.SendHeaderWithDtl();
MESDataModel.Cmd = 3; //(int)Model.MESDataModel.CMDType.烘烤数据上传;
List<Model.MESDataModel.SendListItem> sendListItems =
new List<Model.MESDataModel.SendListItem>();
for (int i = 0; i < Dt.Columns.Count; i++)
{
Model.MESDataModel.SendListItem sendListItem = new MESDataModel.SendListItem();
sendListItem.DataPreporty = Dt.Columns[i].ColumnName;
sendListItem.DataValue = Dt.Rows[0][i].ToString();
sendListItems.Add(sendListItem);
}
MESDataModel.DataList = sendListItems;
//proxy.Invoke("Receive", MESDataModel);
MESFeedback mesFeedBack = await Send(sendHeaderWithDtl);
string result = mesFeedBack.MesResult.ToString();
Model.GuanYu.GYInterfaceModel.RtnZHComm rt = JsonConvert.DeserializeObject<Model.GuanYu.GYInterfaceModel.RtnZHComm>(result);
string value = rt.code;
string value2 = rt.msg;
List<string> valueList = rt.ProjCode;
}
/// <summary>
/// 获取水分检验结果
/// </summary>
/// <param name="JSONPara"></param>
/// <returns></returns>
public async Task<Model.GuanYu.GYInterfaceModel.RtnWaterInfo> GetWaterResult(string JSONPara)
{
Model.MESDataModel.SendHeaderWithDtl sendHeaderWithDtl = new SendHeaderWithDtl();
sendHeaderWithDtl.Cmd = 5; //(int)Model.MESDataModel.CMDType.获取水分结果;
Model.MESDataModel.SendListItem sendListItem = new SendListItem();
sendListItem.DataPreporty = "strCellName";
sendListItem.DataValue = JSONPara;
List<Model.MESDataModel.SendListItem> sendListItems = new List<SendListItem>();
sendListItems.Add(sendListItem);
sendHeaderWithDtl.DataList = sendListItems;
MESFeedback mesFeedBack = await Send(sendHeaderWithDtl);
string result = mesFeedBack.MesResult.ToString();
Model.GuanYu.GYInterfaceModel.RtnWaterInfo rt = JsonConvert.DeserializeObject<Model.GuanYu.GYInterfaceModel.RtnWaterInfo>(result);
//result = "";
//string valueCode = rt.code;
//string valueMsg = rt.msg;
//var valueList = rt.Data;
// Model.GuanYu.GYInterfaceModel.DataItems returnItems = rt.Data;
//string waterContent = returnItems.Water_Content;
return rt;
}
public async Task<string> GetWaterResult2(string code, string projCode)
{
Model.MESDataModel.SendHeaderWithDtl sendHeaderWithDtl = new SendHeaderWithDtl();
sendHeaderWithDtl.Cmd = 2; //(int)Model.MESDataModel.CMDType.电芯条码校验;
string computerName = System.Environment.MachineName;
List<Model.MESDataModel.SendListItem> sendListItems = new List<Model.MESDataModel.SendListItem>
{
new SendListItem{ DataPreporty="CellName",DataValue=code },//电芯条码
new SendListItem{ DataPreporty="ProjCode",DataValue=projCode },//电芯型号
new SendListItem{ DataPreporty="infoData1",DataValue="0" },//周次樊工说不用传。3C才需要
new SendListItem{ DataPreporty="ComputerName",DataValue=computerName }//计算机名
};
sendHeaderWithDtl.DataList = sendListItems;
MESFeedback mesFeedBack = await Send(sendHeaderWithDtl);
string result = mesFeedBack.MesResult.ToString();
Model.GuanYu.GYInterfaceModel.RtnZHComm rt = JsonConvert.DeserializeObject<Model.GuanYu.GYInterfaceModel.RtnZHComm>(result);
string successfulCode = rt.code;
string msg = rt.msg;
if (successfulCode == "0")
{
msg = "true";
}
return msg;
}
public async Task<MESFeedback> Send(SendHeaderWithDtl data)
{
MESFeedback task = null;
if (proxy == null)
{
return task;
}
try
{
task = await proxy.Invoke<MESFeedback>("Receive", data);
}
catch (Exception ex)//进到这里表示连接异常
{
//task = new MESFeedback { Status = "404", MesResult = ex.Message };
}
return task;
}
}
}

View File

@@ -0,0 +1,19 @@
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SignalRClient.HubMethods
{
/// <summary>
/// 这个类和方法组合
/// </summary>
public abstract class IHubClient
{
protected IHubProxy proxy { set; get; }
public abstract void Init(IHubProxy hubProxy);
public abstract void BeginRegister();
}
}

View File

@@ -0,0 +1,179 @@
using Autofac;
using Microsoft.AspNet.SignalR.Client;
using StandardDomeNewApp.Communication.SignalRClient.HubMethods;
using StandardDomeNewApp.Core;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SignalRClient
{
public class SignalRClientConnection
{
public string KeyName { set; get; }
/// <summary>
/// 配置模型
/// </summary>
private ConfigInfoModel configInfoModel { set; get; } = ConfigInfoModel.CreateObj();
/// <summary>
/// 传入用于创建对象的模型
/// </summary>
private SignalRClientModel signalRClientModel { set; get; }
/// <summary>
/// 集线器
/// </summary>
private IHubProxy proxy { set; get; }
/// <summary>
/// 连接器
/// </summary>
private HubConnection connection { set; get; }
public Dictionary<string, IHubClient> RegisterClientDic { set; get; } = new Dictionary<string, IHubClient>();
/// <summary>
/// 客户端的方法注册器
/// </summary>
//public RegisterClient registerMethodClient { set; get; }
/// <summary>
/// 这个对象是否连接
/// </summary>
public bool IsConnect { set; get; }
private DateTime lastTime { set; get; } = DateTime.MinValue;
/// <summary>
/// 构造
/// </summary>
/// <param name="signalRClientModel"></param>
public SignalRClientConnection(SignalRClientModel signalRClientModel)
{
this.signalRClientModel = signalRClientModel;
KeyName = signalRClientModel.ServerKey;
}
/// <summary>
/// 连接服务
/// </summary>
public async Task<bool> ConnectServer()
{
if (signalRClientModel == null)
{
configInfoModel.ShowInvoke?.Invoke("创建对象所需的模型对象为空!", false, SysEnumInfon.MessageLogType.Warn);
IsConnect = false;
return false;
}
try
{
//创建连接器
connection = new HubConnection(signalRClientModel.ServerURI);
var serverHubNames = signalRClientModel.ServerHubName.Split(',');
var funcs = signalRClientModel.ClientRegister.Split('.');
if (funcs.Length != serverHubNames.Length)
{
throw new Exception("配置异常!集线器个数和对应的方法不是一一对应");
}
for (int i = 0; i < serverHubNames.Length; i++)
{
var name = serverHubNames[i];
var fname = funcs[i];
//根据hub名创建代理一些操作由这个代理来做
proxy = connection.CreateHubProxy(name);
//创建方法对象
assembly = configInfoModel.assembly;
var registerMethodClient = CreateRegisterClient(fname);
registerMethodClient.Init(proxy);
registerMethodClient.BeginRegister();//已经初始化了服务器调用客户端的方法
RegisterClientDic[fname] = registerMethodClient;
}
await connection.Start();
IsConnect = true;
return true;
}
catch (Exception ex)
{
IsConnect = false;
configInfoModel.ShowInvoke?.Invoke("创建SignalR客户端对象时发生异常详情" + ex.Message, false, SysEnumInfon.MessageLogType.Warn);
return false;
}
}
/// <summary>
/// 断开服务
/// </summary>
public bool UnconnectServer()
{
if (connection == null)
{
configInfoModel.ShowInvoke?.Invoke("请连接后再尝试断开!", false, SysEnumInfon.MessageLogType.Warn);
return false;
}
IsConnect = false;
try
{
connection.Stop();
return true;
}
catch (Exception ex)
{
configInfoModel.ShowInvoke?.Invoke("断开失败!详情:" + ex.Message, false, SysEnumInfon.MessageLogType.Warn);
return false;
}
}
public async Task ConnectStart()
{
//addwangzi
if(connection.State == ConnectionState.Disconnected)
{
IsConnect = false;
}
if (IsConnect)
{
return;
}
if ((DateTime.Now - lastTime).TotalSeconds > 15)
{
lastTime = DateTime.Now;
try
{
await connection?.Start();
IsConnect = true;
}
catch (Exception ex)
{
IsConnect = false;
configInfoModel.ShowInvoke?.Invoke("创建SignalR客户端对象时发生异常详情" + ex.Message, false, SysEnumInfon.MessageLogType.Warn);
}
}
}
/// <summary>
///
/// </summary>
private Assembly assembly { set; get; }
/// <summary>
/// 创建某种类型的对象 Autofac的作用就是按照一个名字创建一个类相当于替换new关键字而创建一个类
/// 其内部还是很多if构成的加上反射。犹如工厂模式
/// 简而言之 以下代码相当于HubMethods.HubClient hubClient = new HubClient(); 返回了 hubClient
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private IHubClient CreateRegisterClient(string name)
{
IHubClient client = null;
ContainerBuilder builder = new ContainerBuilder();
//builder.RegisterAssemblyTypes(assembly).As<IPLCController>().InstancePerDependency();
if (!string.IsNullOrEmpty(name))
{
name = name.Trim().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); ;
}
var type = assembly.GetType("StandardDomeNewApp.Communication.SignalRClient.HubMethods." + name);
builder.RegisterType(type).As<IHubClient>().InstancePerDependency();
using (IContainer container = builder.Build())
{
client = container.Resolve<IHubClient>();
}
return client;
}
}
}

View File

@@ -0,0 +1,183 @@
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.Sockets
{
public class ProvidOrdinaryClient
{
/// <summary>
/// 客户端
/// </summary>
private AsyncTcpSession client;
/// <summary>
/// socket服务地址
/// </summary>
public string Ipaddress { set; get; }
/// <summary>
/// socket服务端口
/// </summary>
public int Portnumber { set; get; }
public int BindPort { set; get; }
/// <summary>
/// 服务是否连接
/// </summary>
private bool IsConnectserver;
/// <summary>
/// 服务是否连接
/// </summary>
public bool IsconnectServer
{
get => IsConnectserver;
private set
{
IsConnectserver = value;
IsconnectserverAction?.Invoke(value);
}
}
/// <summary>
/// 连接状态的委托
/// </summary>
public Action<bool> IsconnectserverAction { set; get; }
/// <summary>
/// 连接成功后的委托
/// </summary>
public Action Connectaction { set; get; }
/// <summary>
/// 关闭连接后的委托
/// </summary>
public Action CloseConnectAction { set; get; }
/// <summary>
/// 错误消息委托
/// </summary>
public Action<string> ErrorMessageAction { set; get; }
/// <summary>
/// 获取消息委托(这个委托是和事件一个线程的,需要分离数据处理的情况时请在委托里开线程解决)
/// </summary>
public Action<byte[], Encoding> GetMessages { set; get; }
/// <summary>
/// 发送时的字符串编码随时可以改的只要拿到了socket对象就可以改改了后下次的发送就是修改后的编码了
/// </summary>
public Encoding encoding { private set; get; }
/// <summary>
/// 消息委托
/// </summary>
public Action<string, bool, Core.SysEnumInfon.MessageLogType> ShowMessageAction { set; get; }
/// <summary>
/// 客户端名称
/// </summary>
private string clientName { set; get; }
private bool IsInitComplete { set; get; } = false;
public ProvidOrdinaryClient(string encodingstrname)
{
encoding = string.IsNullOrEmpty(encodingstrname) ? Encoding.Default : Encoding.GetEncoding(encodingstrname);
Init();
}
public ProvidOrdinaryClient(Encoding encoding = null)
{
this.encoding = encoding == null ? Encoding.Default : encoding;
Init();
}
private void Init()
{
client = new AsyncTcpSession();
// 连接断开事件
client.Closed += client_Closed;
// 收到服务器数据事件
client.DataReceived += client_DataReceived;
// 连接到服务器事件
client.Connected += client_Connected;
// 发生错误的处理
client.Error += client_Error;
}
private void client_Error(object sender, ErrorEventArgs e)
{
ErrorMessageAction?.Invoke(e.Exception.Message);
ShowMessageAction?.Invoke(e.Exception.Message, false, Core.SysEnumInfon.MessageLogType.Error);
}
private void client_Connected(object sender, EventArgs e)
{
IsconnectServer = client.IsConnected;
Connectaction?.Invoke();
ShowMessageAction?.Invoke($"对象{clientName}连接 {IsconnectServer}", false, Core.SysEnumInfon.MessageLogType.Info);
}
private void client_DataReceived(object sender, DataEventArgs e)
{
var buffer = e.Data.Take(e.Length).ToArray();
GetMessages?.Invoke(buffer, encoding);
}
private void client_Closed(object sender, EventArgs e)
{
IsconnectServer = false;
CloseConnectAction?.Invoke();
ShowMessageAction?.Invoke($"对象{clientName}断开连接", false, Core.SysEnumInfon.MessageLogType.Info);
}
public void Connect(string clientname, string ip, int port, int bindport = -1)
{
if (bindport >= 0)
{
client.LocalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), bindport);
}
client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
Ipaddress = ip;
Portnumber = port;
clientName = clientname;
BindPort = bindport;
IsInitComplete = true;
}
/// <summary>
/// 断开连接
/// </summary>
public void CloseConnect()
{
client?.Close();
IsInitComplete = false;
}
/// <summary>
/// 向服务器发命令行协议的数据
/// </summary>
/// <param name="key">命令名称 默认没有为空</param>
/// <param name="data">数据</param>
public void SendCommand(string data, string key = null)
{
if (string.IsNullOrEmpty(data))
{
return;
}
if (client.IsConnected)
{
if (!string.IsNullOrEmpty(key))
{
//命令 内容
var arr = encoding.GetBytes(string.Format("{0} {1}", key, data));
client.Send(new ArraySegment<byte>(arr));
}
else
{
var arr = encoding.GetBytes(string.Format("{0}", data));
client.Send(new ArraySegment<byte>(arr));
}
}
}
public void ReConnect()
{
if (!IsconnectServer && IsInitComplete)
{
Connect(clientName, Ipaddress, Portnumber, BindPort);
}
}
}
}

View File

@@ -0,0 +1,450 @@
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.Sockets
{
public class SingleSocketServer
{
public SingleSocketServer(string encoding = null)
{
this.encoding = string.IsNullOrEmpty(encoding) ? Encoding.Default : Encoding.GetEncoding(encoding);
}
/// <summary>
/// 服务类型 1是supersocket 2是iocp
/// </summary>
private int serverType { set; get; }
/// <summary>
/// 解码方式
/// </summary>
public Encoding encoding { private set; get; }
/// <summary>
/// 服务对象
/// </summary>
private AppServer appServer { set; get; }
/// <summary>
///
/// </summary>
private socket.core.Server.TcpPushServer iocpServer { set; get; }
/// <summary>
///
/// </summary>
private Regex regex { set; get; } = new Regex(@"^%.*|.*%$");
/// <summary>
/// 会话字典
/// </summary>
public Dictionary<string, string> SessionIDDic { private set; get; } = new Dictionary<string, string>();
/// <summary>
/// 消息委托
/// </summary>
public Action<string, bool, Core.SysEnumInfon.MessageLogType> ShowMessageAction { set; get; }
/// <summary>
/// 接收消息委托 二进制数组的
/// </summary>
public Action<string, string> RequestReceivedAction { set; get; }
/// <summary>
/// 会话进来
/// </summary>
public Action<string> OnSessionAccept { set; get; }
/// <summary>
/// 会话结束
/// </summary>
public Action<string> OnSessionClose { set; get; }
public bool IsOpenServer { private set; get; }
public string ServerName { private set; get; }
/// <summary>
/// 是否允许接收字典
/// </summary>
public ConcurrentDictionary<string, bool> IsAllowReceiveDic { set; get; } = new ConcurrentDictionary<string, bool>();
/// <summary>
/// 会话数据字典
/// </summary>
public ConcurrentDictionary<string, string> SessionDataDic { set; get; } = new ConcurrentDictionary<string, string>();
#region
/// <summary>
/// 启动服务
/// </summary>
/// <param name="port">服务端口</param>
/// <param name="enddata">servertype为2时才有意义 结尾符</param>
public void StartServer(string serverkey, int port, byte[] enddata = null)
{
ServerName = serverkey;
if (enddata == null)
{
//当为空时使用iocp的方式
serverType = 2;
iocpServer = new socket.core.Server.TcpPushServer(100, 1024 * 2, 0);
if (ushort.TryParse(port.ToString(), out ushort port2))
{
try
{
iocpServer.Start(port);
}
catch (Exception ex)
{
ShowMessageAction?.Invoke("启动失败!" + ex.Message, false, Core.SysEnumInfon.MessageLogType.Warn);
}
IsOpenServer = true;
iocpServer.OnAccept += IocpServer_OnAccept;
iocpServer.OnClose += IocpServer_OnClose;
iocpServer.OnReceive += IocpServer_OnReceive;
}
else
{
ShowMessageAction?.Invoke("端口输入范围在0-65535的值", false, Core.SysEnumInfon.MessageLogType.Warn);
}
return;
}
//使用supersocket组件
serverType = 1;
if (enddata.Length < 1)
{
appServer = new AppServer();
}
else
{
appServer = new AppServer(new TerminatorReceiveFilterFactory(encoding.GetString(enddata)));
}
appServer.NewRequestReceived += AppServer_NewRequestReceived;
appServer.NewSessionConnected += AppServer_NewSessionConnected;
appServer.SessionClosed += AppServer_SessionClosed;
var serverconfig = new SuperSocket.SocketBase.Config.ServerConfig();
serverconfig.Port = port;
serverconfig.TextEncoding = encoding.EncodingName;
if (ushort.TryParse(port.ToString(), out ushort port1))
{
if (!appServer.Setup(serverconfig))
{
ShowMessageAction?.Invoke("设置错误!", false, Core.SysEnumInfon.MessageLogType.Warn);
return;
}
if (!appServer.Start())
{
ShowMessageAction?.Invoke("启动失败!", false, Core.SysEnumInfon.MessageLogType.Warn);
return;
}
IsOpenServer = true;
}
else
{
ShowMessageAction?.Invoke("端口输入范围在0-65535的值", false, Core.SysEnumInfon.MessageLogType.Warn);
}
}
/// <summary>
/// 结束服务
/// </summary>
public void StopServer()
{
if (!IsOpenServer)
{
ShowMessageAction?.Invoke("当前状态不需要断开监听!", false, Core.SysEnumInfon.MessageLogType.Info);
return;
}
if (serverType == 1)
{
appServer.Stop();
appServer.Dispose();
appServer = null;
}
else if (serverType == 2)
{
var dic = new Dictionary<int, string>(iocpServer.ClientList);
foreach (var item in dic)
{
iocpServer.Close(item.Key);
}
}
IsOpenServer = false;
}
/// <summary>
/// 会话发送
/// </summary>
/// <param name="datas"></param>
/// <param name="sessionid">为空时为广播</param>
public void SessionSend(byte[] datas, string sessionid = null)
{
if (datas == null || datas.Length < 1)
{
ShowMessageAction?.Invoke("数据为空,无效发送!", false, Core.SysEnumInfon.MessageLogType.Info);
return;
}
if (string.IsNullOrEmpty(sessionid))
{
if (serverType == 1)
{
var allsessions = appServer.GetAllSessions();
foreach (var item in allsessions)
{
item.Send(encoding.GetString(datas));
}
}
else if (serverType == 2)
{
foreach (var item in iocpServer.ClientList)
{
iocpServer.Send(item.Key, datas, 0, datas.Length);
}
}
}
else
{
if (serverType == 1)
{
var one = appServer.GetSessionByID(sessionid);
if (one != null)
{
one.Send(encoding.GetString(datas));
}
else
{
ShowMessageAction?.Invoke("请检查传入的会话ID是否有效当前无法查询到相关会话信息无效发送", false, Core.SysEnumInfon.MessageLogType.Info);
}
}
else if (serverType == 2)
{
if (int.TryParse(sessionid, out int num) && iocpServer.ClientList.ContainsKey(num))
{
iocpServer.Send(num, datas, 0, datas.Length);
}
else
{
ShowMessageAction?.Invoke("请检查传入的会话ID是否有效当前无法查询到相关会话信息无效发送", false, Core.SysEnumInfon.MessageLogType.Info);
}
}
}
}
/// <summary>
/// 会话发送
/// </summary>
/// <param name="datas"></param>
/// <param name="sessionid">为空时为广播</param>
public void SessionSend(string datas, string sessionid = null)
{
if (string.IsNullOrEmpty(datas))
{
ShowMessageAction?.Invoke("数据为空,无效发送!", false, Core.SysEnumInfon.MessageLogType.Info);
return;
}
if (string.IsNullOrEmpty(sessionid))
{
if (serverType == 1)
{
var allsessions = appServer.GetAllSessions();
foreach (var item in allsessions)
{
item.Send(datas);
}
}
else if (serverType == 2)
{
foreach (var item in iocpServer.ClientList)
{
iocpServer.Send(item.Key, encoding.GetBytes(datas), 0, datas.Length);
}
}
}
else
{
if (serverType == 1)
{
var one = appServer.GetSessionByID(sessionid);
if (one != null)
{
one.Send(datas);
}
else
{
ShowMessageAction?.Invoke("请检查传入的会话ID是否有效当前无法查询到相关会话信息无效发送", false, Core.SysEnumInfon.MessageLogType.Info);
}
}
else if (serverType == 2)
{
if (int.TryParse(sessionid, out int num) && iocpServer.ClientList.ContainsKey(num))
{
iocpServer.Send(num, encoding.GetBytes(datas), 0, datas.Length);
}
else
{
ShowMessageAction?.Invoke("请检查传入的会话ID是否有效当前无法查询到相关会话信息无效发送", false, Core.SysEnumInfon.MessageLogType.Info);
}
}
}
}
/// <summary>
/// 返回地址对应的sessionid 可能返回为空
/// </summary>
/// <param name="ipaddress"></param>
/// <returns></returns>
public string GetSessionID(string ipaddress)
{
string sessionid = null;
var datas = SessionIDDic.Where(d => d.Value == ipaddress);
if (datas != null)
{
var list = datas.ToList();
if (list.Count > 0)
{
var oneitem = list.ElementAt(0);
sessionid = oneitem.Key;
}
}
return sessionid;
}
/// <summary>
/// 返回id对应的地址 可能返回为空
/// </summary>
/// <param name="sessionid"></param>
/// <returns></returns>
public string GetIpAddress(string sessionid)
{
if (SessionIDDic.ContainsKey(sessionid))
{
return SessionIDDic[sessionid];
}
return null;
}
#endregion
#region
/// <summary>
/// 会话关闭
/// </summary>
/// <param name="session"></param>
/// <param name="value"></param>
private void AppServer_SessionClosed(AppSession session, CloseReason value)
{
if (SessionIDDic.ContainsKey(session.SessionID))
{
SessionIDDic.Remove(session.SessionID);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("会话:");
stringBuilder.Append(session.SessionID);
stringBuilder.Append("(");
stringBuilder.Append(session.RemoteEndPoint.Address);
stringBuilder.Append(":");
stringBuilder.Append(session.RemoteEndPoint.Port.ToString());
stringBuilder.Append(")");
stringBuilder.Append("关闭!关闭原因:");
stringBuilder.Append(value.ToString());
ShowMessageAction?.Invoke(stringBuilder.ToString(), false, Core.SysEnumInfon.MessageLogType.Info);
OnSessionClose?.Invoke(session.SessionID);
}
}
private void IocpServer_OnClose(int obj)
{
if (SessionIDDic.ContainsKey(obj.ToString()))
{
SessionIDDic.Remove(obj.ToString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("会话:");
stringBuilder.Append(obj.ToString());
stringBuilder.Append("(");
if (iocpServer.ClientList.ContainsKey(obj))
{
stringBuilder.Append(iocpServer.ClientList[obj]);
}
stringBuilder.Append(")");
stringBuilder.Append("关闭!关闭原因:用户退出!");
ShowMessageAction?.Invoke(stringBuilder.ToString(), false, Core.SysEnumInfon.MessageLogType.Info);
OnSessionClose?.Invoke(obj.ToString());
}
}
/// <summary>
/// 会话新连接
/// </summary>
/// <param name="session"></param>
private void AppServer_NewSessionConnected(AppSession session)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(session.RemoteEndPoint.Address);
stringBuilder.Append(":");
stringBuilder.Append(session.RemoteEndPoint.Port.ToString());
string info = stringBuilder.ToString();
//记录会话id与物理地址的关系
SessionIDDic[session.SessionID] = info;
stringBuilder.Remove(0, stringBuilder.Length);
stringBuilder.Append("新进会话:");
stringBuilder.Append(session.SessionID);
stringBuilder.Append("(");
stringBuilder.Append(info);
stringBuilder.Append(")");
ShowMessageAction?.Invoke(stringBuilder.ToString(), false, Core.SysEnumInfon.MessageLogType.Info);
OnSessionAccept?.Invoke(session.SessionID);
}
/// <summary>
/// 新的会话进来
/// </summary>
/// <param name="obj"></param>
private void IocpServer_OnAccept(int obj)
{
StringBuilder stringBuilder = new StringBuilder();
if (!iocpServer.ClientList.ContainsKey(obj))
{
return;
}
stringBuilder.Append(iocpServer.ClientList[obj]);
string info = stringBuilder.ToString();
//记录会话id与物理地址的关系
SessionIDDic[obj.ToString()] = info;
stringBuilder.Remove(0, stringBuilder.Length);
stringBuilder.Append("新进会话:");
stringBuilder.Append(obj.ToString());
stringBuilder.Append("(");
stringBuilder.Append(info);
stringBuilder.Append(")");
ShowMessageAction?.Invoke(stringBuilder.ToString(), false, Core.SysEnumInfon.MessageLogType.Info);
OnSessionAccept?.Invoke(obj.ToString());
}
/// <summary>
/// 会话信息接收
/// </summary>
/// <param name="session"></param>
/// <param name="requestInfo"></param>
private void AppServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
{
var sessionid = session.SessionID;
var bdatas = requestInfo.Key + "%" + requestInfo.Body;
if (string.IsNullOrEmpty(bdatas))
{
//空数据不解析
return;
}
if (regex.IsMatch(bdatas))
{
//如果有%在头或者尾
bdatas = bdatas.Replace("%", "").Trim();
}
RequestReceivedAction(sessionid, bdatas);
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
private void IocpServer_OnReceive(int arg1, byte[] arg2)
{
RequestReceivedAction(arg1.ToString(), encoding.GetString(arg2));
}
#endregion
}
}

View File

@@ -0,0 +1,115 @@
using StandardDomeNewApp.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static StandardDomeNewApp.Core.SysEnumInfon;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public abstract class IScanCode
{
/// <summary>
/// plc的唯一标识
/// </summary>
public string KeyName { set; get; }
/// <summary>
/// 缓存
/// </summary>
protected ContentCache contentCache { set; get; } = ContentCache.CreateObj();
/// <summary>
/// 是否使用虚拟码 true使用
/// </summary>
protected bool IsUserVCode { set; get; } = false;
/// <summary>
/// 模拟
/// </summary>
protected bool IsSimulation { set; get; } = false;
/// <summary>
/// 这个对象最大额虚拟码
/// </summary>
protected int MaxVCode { set; get; }
/// <summary>
/// 这个对象最小的虚拟码
/// </summary>
protected int MinVCode { set; get; }
/// <summary>
/// 是否忙(用在手动触发时判断一下)
/// </summary>
public bool IsBusy { set; get; }
/// <summary>
/// 当前的虚拟码
/// </summary>
public virtual int Vcode { set; get; }
/// <summary>
/// 当前字符解码方式
/// </summary>
public Encoding oneEncoding { set; get; } = Encoding.Default;
/// <summary>
/// 最大试错次数
/// </summary>
public int MaxReadCount { set; get; } = 3;
/// <summary>
/// 是否连接
/// </summary>
public virtual bool IsConnect { protected set; get; }
/// <summary>
/// 消息显示委托
/// </summary>
public Action<string, bool, MessageLogType> ShowMessageAction { set; get; }
/// <summary>
/// 获取原始数据 做服务时用@分割id和数据
/// </summary>
public Action<byte[], Encoding> GetOriginalData { set; get; }
/// <summary>
/// 错误代码合集
/// </summary>
public List<string> ErrorCodes { set; get; } = new List<string>();
/// <summary>
/// 构建这个对象
/// </summary>
public abstract void Build(object config);
/// <summary>
/// 连接扫码枪
/// </summary>
/// <returns></returns>
public abstract bool Connect();
/// <summary>
/// 断开扫码枪
/// </summary>
/// <returns></returns>
public abstract bool UnConnect();
/// <summary>
/// 读取条码
/// </summary>
/// <returns></returns>
public abstract Tuple<string,int,bool> ReadCode();
/// <summary>
/// 重连
/// </summary>
public abstract void ReConnect();
/// <summary>
/// 设定是否使用虚拟码
/// </summary>
/// <param name="state"></param>
public virtual void SetIsUserVCode(bool state)
{
IsUserVCode = state;
}
/// <summary>
/// 设置模拟/真实
/// </summary>
/// <param name="state"></param>
public virtual void SetIsSimulation(bool state)
{
IsSimulation = state;
}
public virtual bool GetIsSimulation()
{
return IsSimulation;
}
}
}

View File

@@ -0,0 +1,345 @@
using StandardDomeNewApp.Communication.Sockets;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_ClientSocket : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 读取操作的锁
/// </summary>
private object readopLock { set; get; } = new object();
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 网口客户端对象
/// </summary>
private ProvidOrdinaryClient providOrdinaryClient { set; get; }
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
/// <summary>
/// 一个客户端接收数据也是一个个来的
/// </summary>
private string dataPack { set; get; }
/// <summary>
/// 是否允许开始接收了
/// </summary>
private bool IsAllowReceive { set; get; } = false;
/// <summary>
/// 条码的长度
/// </summary>
private int QRcodeLength = int.Parse(Login.GetParaValue("QRCodeLength"));
/// <summary>
/// 建立对象
/// </summary>
/// <param name="config"></param>
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
Util.CommonHelper.Fatal("ScanCode_ClientSocket","Error 1:"+ "请先Build后再尝试连接");
return false;
}
providOrdinaryClient = contentCache.GetContent<ProvidOrdinaryClient>(configModel.ProtocolKey);
if (providOrdinaryClient == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的网口客户端对象!", false, Core.SysEnumInfon.MessageLogType.Info);
Util.CommonHelper.Fatal("ScanCode_ClientSocket", "Error 2:" + $"无法找到[{configModel.ProtocolKey}]对应的网口客户端对象!");
return false;
}
providOrdinaryClient.IsconnectserverAction = b =>
{
IsConnect = b;
ShowMessageAction?.Invoke($"扫码枪对象[{KeyName}]连接状态:{IsConnect}", false, Core.SysEnumInfon.MessageLogType.Info);
Util.CommonHelper.Fatal("ScanCode_ClientSocket", "Error 3:" + $"扫码枪对象[{KeyName}]连接状态:{IsConnect}");
};
providOrdinaryClient.GetMessages = RawData_Receive;
IsConnect = providOrdinaryClient.IsconnectServer;
oneEncoding = providOrdinaryClient.encoding;
ShowMessageAction?.Invoke($"扫码枪对象[{KeyName}]连接状态:{IsConnect}", false, Core.SysEnumInfon.MessageLogType.Info);
Util.CommonHelper.Fatal("ScanCode_ClientSocket", "Error 4:" + $"扫码枪对象[{KeyName}]连接状态:{IsConnect}");
return IsConnect;
}
/// <summary>
/// 读取条码 (同步完成的) 自动扫码
/// </summary>
/// <returns></returns>
public Tuple<string,int,bool> ReadCode3()//去掉了 override
{
lock (readopLock)
{
IsBusy = true;
string dataPackResult = "";
for (int i = 0; i < MaxReadCount; i++)
{
//发送命令
if (!string.IsNullOrEmpty(configModel.Command))
{
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
providOrdinaryClient.SendCommand(command + Environment.NewLine);
}
else
{
providOrdinaryClient.SendCommand(command);
}
}
//开始允许接收
IsAllowReceive = true;
//记录开始的时间
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
//超过预定的时间跳出等待
break;
}
//正则表达式,基本用不到
//直接拿过来
if (!string.IsNullOrEmpty(dataPack))
{
//只要有数据来就进来解析
dataPackResult = dataPack;//dataPack在RawData_Receive函数接收
var find = ErrorCodes.Find(o => dataPackResult.Contains(o));
if (find == null)
{
//如果读到了数据就跳出来,以下语句挑出两层循环
goto OutPutData;
}
}
Thread.Sleep(5);
}
}
OutPutData:
//读取完成无论成功与否都结束接收
IsAllowReceive = false;
//清除缓存
dataPack = string.Empty;
IsBusy = false;
//这个时候拿出(返回)数据包
return Tuple.Create(dataPackResult,-1,true);
}
}
/// <summary>
/// 手动扫码
/// </summary>
/// <returns></returns>
public override Tuple<string, int, bool> ReadCode()
{
lock (readopLock)
{
IsBusy = true;
string dataPackResult = "";
//开始允许接收
//IsAllowReceive = true;
//正则表达式,基本用不到
//直接拿过来
if (!string.IsNullOrEmpty(dataPack))
{
//只要有数据来就进来解析
dataPackResult = dataPack;//dataPack在RawData_Receive函数接收
var find = ErrorCodes.Find(o => dataPackResult.Contains(o));
if (find == null)
{
//如果读到了数据就跳出来,以下语句挑出两层循环
goto OutPutData;
}
}
OutPutData:
//读取完成无论成功与否都结束接收
IsAllowReceive = false;
//清除缓存
dataPack = string.Empty;
IsBusy = false;
//这个时候拿出(返回)数据包
bool flag = false;
if (dataPackResult.Length>=3)
{
flag = true;
}
return Tuple.Create(dataPackResult, -1, flag);
}
}
public override void ReConnect()
{
providOrdinaryClient?.ReConnect();
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public override bool UnConnect()
{
if (providOrdinaryClient == null)
{
return false;
}
providOrdinaryClient.CloseConnect();
IsConnect = false;
return true;
}
/// <summary>
/// 原始数据接收
/// </summary>
/// <param name="data"></param>
/// <param name="encoding"></param>
private void RawData_Receive(byte[] data, Encoding encoding)
{
GetOriginalData?.Invoke(data, encoding);
//if (!IsAllowReceive)
//{
// return;
//}
dataPack += encoding.GetString(data);
//if (encoding.BodyName=="utf-8")// addwang 读取刷卡机
//{
// StringBuilder builder = new StringBuilder();
// for (int i = 0; i < data.Length; i++)
// {
// builder.Append(string.Format("{0:X2} ", data[i]));
// }
// dataPack = builder.ToString().Trim();
//}
//else
//{
// dataPack += encoding.GetString(data);
//}
}
/// <summary>
///
/// </summary>
/// <param name="byteDatas"></param>
/// <returns></returns>
}
}

View File

@@ -0,0 +1,245 @@
using Keyence.AutoID.SDK;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_Keyence : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 基恩士扫码枪的读取器
/// </summary>
private ReaderAccessor reader { set; get; }
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
reader = new ReaderAccessor();
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
KeyenceConnectModel keyence = contentCache.GetContent<KeyenceConnectModel>(configModel.ProtocolKey);
if (keyence != null)
{
reader.CommandPort = reader.DataPort = keyence.Port;
}
oneEncoding = Encoding.ASCII;//sdk里写死的
return IsConnect = reader.Connect();
}
public override Tuple<string, int, bool> ReadCode()
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
if (IsSimulation)
{
//模拟
isok = true;
datapack = Guid.NewGuid().ToString();
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
}
else
{
for (int i = 0; i < MaxReadCount; i++)
{
var cmd = configModel.Command.Split('+')[0];
var code = reader.ExecCommand(cmd, configModel.OutTime);
if (regex == null)
{
var find = ErrorCodes.Find(o => o == code);
if (find == null)
{
datapack = code;
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
isok = true;
break;
}
}
else
{
var result = regex.Match(code);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.CodeRegex.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => o == str);
if (find == null)
{
datapack = str;
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
isok = true;
break;
}
}
}
}
}
IsBusy = false;
return Tuple.Create(datapack, vcode, isok);
}
public override void ReConnect()
{
if (!IsConnect)
{
reader.Connect();
}
}
public override bool UnConnect()
{
try
{
reader.Disconnect();
reader.Dispose();
return true;
}
catch (Exception)
{
return false;
}
}
}
}

View File

@@ -0,0 +1,313 @@
using StandardDomeNewApp.Communication.SerialPorts;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_SeriaPort : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 读取操作的锁
/// </summary>
private object readopLock { set; get; } = new object();
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 串口对象
/// </summary>
private SeriaPortController seriaPortController { set; get; }
/// <summary>
/// 一个串口的数据包 一个串口write有多个线程写都是会按照顺序写完一个包再写一个包的
/// </summary>
private string dataPack { set; get; }
/// <summary>
/// 是否允许开始接收了
/// </summary>
private bool IsAllowReceive { set; get; } = false;
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
/// <summary>
/// 建立对象
/// </summary>
/// <param name="config"></param>
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
seriaPortController = contentCache.GetContent<SeriaPortController>(configModel.ProtocolKey);
if (seriaPortController == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的串口对象!", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
seriaPortController.RawDataAction = RawData_Receive;
IsConnect = true;
oneEncoding = seriaPortController.encoding;
return true;
}
/// <summary>
/// 读取条码 (同步完成的)
/// </summary>
/// <returns></returns>
public override Tuple<string, int, bool> ReadCode()
{
lock (readopLock)
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
if (IsSimulation)
{
//模拟
isok = true;
datapack = Guid.NewGuid().ToString();
}
else
{
for (int i = 0; i < MaxReadCount; i++)
{
bool flag = false;
//发送命令
if (!string.IsNullOrEmpty(configModel.Command))
{
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
seriaPortController.Send(command + Environment.NewLine);
}
else
{
seriaPortController.Send(command);
}
}
//开始允许接收
IsAllowReceive = true;
//记录开始的时间
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
//超过预定的时间跳出等待
break;
}
if (regex == null)
{
//直接拿过来
if (!string.IsNullOrEmpty(dataPack))
{
//只要有数据来就进来解析
datapack = dataPack;
var find = ErrorCodes.Find(o => datapack.Contains(o));
if (find == null)
{
isok = true;
}
}
}
else
{
var result = regex.Match(dataPack);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.CodeRegex.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => str.Contains(o));
if (find == null)
{
datapack = str;
isok = true;
}
}
}
if (isok)
{
//收到数据了
flag = true;
break;
}
//这个是为了破除最大线程数 防止死循环卡死的
Thread.Sleep(5);
}
if (flag)
{
//如果接收到了数据就跳出尝试循环
break;
}
}
}
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
//读取完成无论成功与否都结束接收
IsAllowReceive = false;
//清除缓存
dataPack = string.Empty;
IsBusy = false;
//这个时候拿出(返回)数据包
return Tuple.Create(datapack, vcode, isok);
}
}
public override void ReConnect()
{
seriaPortController?.ReTryOpen();
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public override bool UnConnect()
{
if (seriaPortController == null)
{
return false;
}
seriaPortController.Close();
IsConnect = false;
return true;
}
/// <summary>
/// 原始数据接收
/// </summary>
/// <param name="data"></param>
/// <param name="encoding"></param>
private void RawData_Receive(byte[] data, Encoding encoding)
{
GetOriginalData?.Invoke(data, encoding);
if (!IsAllowReceive)
{
return;
}
dataPack += encoding.GetString(data);
}
}
}

View File

@@ -0,0 +1,325 @@
using StandardDomeNewApp.Communication.Sockets;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_ServerSocket : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.TSweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 读取操作的锁
/// </summary>
private object readopLock { set; get; } = new object();
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 服务对象
/// </summary>
private SingleSocketServer singleSocketServer { set; get; }
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
singleSocketServer = contentCache.GetContent<SingleSocketServer>(configModel.ProtocolKey);
if (singleSocketServer == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的串口对象!", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
if (singleSocketServer.RequestReceivedAction == null)
{
singleSocketServer.RequestReceivedAction = RequestReceived;
}
if (singleSocketServer.OnSessionAccept == null)
{
singleSocketServer.OnSessionAccept = SessionAccept;
}
if (singleSocketServer.OnSessionClose == null)
{
singleSocketServer.OnSessionClose = SessionClose;
}
oneEncoding = singleSocketServer.encoding;
IsConnect = true;
return true;
}
public override Tuple<string, int, bool> ReadCode()
{
lock (readopLock)
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
if (IsSimulation)
{
//模拟
isok = true;
datapack = Guid.NewGuid().ToString();
}
else
{
var id = singleSocketServer.GetSessionID(configModel.Reserve);
for (int i = 0; i < MaxReadCount; i++)
{
bool flag = false;
//发送命令
if (!string.IsNullOrEmpty(configModel.Command))
{
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
singleSocketServer.SessionSend(command + Environment.NewLine, id);
}
else
{
singleSocketServer.SessionSend(command, id);
}
}
//开始允许接收
singleSocketServer.IsAllowReceiveDic[id] = true;
//记录开始的时间
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
//超过预定的时间跳出等待
break;
}
if (regex == null)
{
//直接拿过来
if (!string.IsNullOrEmpty(singleSocketServer.SessionDataDic[id]))
{
//只要有数据来就进来解析
datapack = singleSocketServer.SessionDataDic[id];
var find = ErrorCodes.Find(o => datapack.Contains(o));
if (find == null)
{
isok = true;
}
}
}
else
{
var result = regex.Match(singleSocketServer.SessionDataDic[id]);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.CodeRegex.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => str.Contains(o));
if (find == null)
{
datapack = str;
isok = true;
}
}
}
if (isok)
{
//收到数据了
flag = true;
break;
}
//这个是为了破除最大线程数 防止死循环卡死的
Thread.Sleep(5);
}
if (flag)
{
//如果接收到了数据就跳出尝试循环
break;
}
}
//读取完成无论成功与否都结束接收
singleSocketServer.IsAllowReceiveDic[id] = false;
//清除缓存
singleSocketServer.SessionDataDic[id] = string.Empty;
}
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
IsBusy = false;
//这个时候拿出(返回)数据包
return Tuple.Create(datapack, vcode, isok);
}
}
public override void ReConnect()
{
//服务不需要
}
public override bool UnConnect()
{
if (singleSocketServer == null)
{
return false;
}
singleSocketServer.StopServer();
IsConnect = false;
return true;
}
private void RequestReceived(string id, string data)
{
GetOriginalData?.Invoke(oneEncoding.GetBytes(id + "@" + data), oneEncoding);
if (singleSocketServer.IsAllowReceiveDic.ContainsKey(id))
{
if (!singleSocketServer.IsAllowReceiveDic[id])
{
//其中一个会话返回
return;
}
if (singleSocketServer.SessionDataDic.ContainsKey(id))
{
singleSocketServer.SessionDataDic[id] += data;
}
}
}
private void SessionAccept(string id)
{
singleSocketServer.IsAllowReceiveDic[id] = false;
singleSocketServer.SessionDataDic[id] = string.Empty;
}
private void SessionClose(string id)
{
if (singleSocketServer.SessionDataDic.ContainsKey(id))
{
singleSocketServer.SessionDataDic.TryRemove(id, out string str);
}
if (singleSocketServer.IsAllowReceiveDic.ContainsKey(id))
{
singleSocketServer.IsAllowReceiveDic.TryRemove(id, out bool state);
}
}
}
}

View File

@@ -0,0 +1,95 @@
using StandardDomeNewApp.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static StandardDomeNewApp.Core.SysEnumInfon;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public abstract class IScanCode
{
/// <summary>
/// plc的唯一标识
/// </summary>
public string KeyName { set; get; }
/// <summary>
/// 缓存
/// </summary>
protected ContentCache contentCache { set; get; } = ContentCache.CreateObj();
/// <summary>
/// 是否使用虚拟码 true使用
/// </summary>
protected bool IsUserVCode { set; get; } = true;
/// <summary>
/// 这个对象最大额虚拟码
/// </summary>
protected int MaxVCode { set; get; }
/// <summary>
/// 这个对象最小的虚拟码
/// </summary>
protected int MinVCode { set; get; }
/// <summary>
/// 是否忙(用在手动触发时判断一下)
/// </summary>
public bool IsBusy { set; get; }
/// <summary>
/// 当前的虚拟码
/// </summary>
public virtual int Vcode { set; get; }
/// <summary>
/// 当前字符解码方式
/// </summary>
public Encoding oneEncoding { set; get; } = Encoding.Default;
/// <summary>
/// 最大试错次数
/// </summary>
public int MaxReadCount { set; get; } = 3;
/// <summary>
/// 是否连接
/// </summary>
public virtual bool IsConnect { protected set; get; }
/// <summary>
/// 消息显示委托
/// </summary>
public Action<string, bool, MessageLogType> ShowMessageAction { set; get; }
/// <summary>
/// 错误代码合集
/// </summary>
public List<string> ErrorCodes { set; get; } = new List<string>();
/// <summary>
/// 构建这个对象
/// </summary>
public abstract void Build(object config);
/// <summary>
/// 连接扫码枪
/// </summary>
/// <returns></returns>
public abstract bool Connect();
/// <summary>
/// 断开扫码枪
/// </summary>
/// <returns></returns>
public abstract bool UnConnect();
/// <summary>
/// 读取条码
/// </summary>
/// <returns></returns>
public abstract Tuple<string, int, bool> ReadCode();
/// <summary>
/// 重连
/// </summary>
public abstract void ReConnect();
/// <summary>
/// 设定是否使用虚拟码
/// </summary>
/// <param name="state"></param>
public virtual void SetIsUserVCode(bool state)
{
IsUserVCode = state;
}
}
}

View File

@@ -0,0 +1,313 @@
using StandardDomeNewApp.Communication.Sockets;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_ClientSocket : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 读取操作的锁
/// </summary>
private object readopLock { set; get; } = new object();
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 网口客户端对象
/// </summary>
private ProvidOrdinaryClient providOrdinaryClient { set; get; }
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
/// <summary>
/// 一个客户端接收数据也是一个个来的
/// </summary>
private string dataPack { set; get; }
/// <summary>
/// 是否允许开始接收了
/// </summary>
private bool IsAllowReceive { set; get; } = false;
/// <summary>
/// 建立对象
/// </summary>
/// <param name="config"></param>
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
providOrdinaryClient = contentCache.GetContent<ProvidOrdinaryClient>(configModel.ProtocolKey);
if (providOrdinaryClient == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的网口客户端对象!", false, Core.SysEnumInfon.MessageLogType.Info);
}
providOrdinaryClient.IsconnectserverAction = b =>
{
IsConnect = b;
ShowMessageAction?.Invoke($"扫码枪对象[{KeyName}]连接状态:{IsConnect}", false, Core.SysEnumInfon.MessageLogType.Info);
};
providOrdinaryClient.GetMessages = RawData_Receive;
IsConnect = providOrdinaryClient.IsconnectServer;
oneEncoding = providOrdinaryClient.encoding;
ShowMessageAction?.Invoke($"扫码枪对象[{KeyName}]连接状态:{IsConnect}", false, Core.SysEnumInfon.MessageLogType.Info);
return true;
}
/// <summary>
/// 读取条码 (同步完成的)
/// </summary>
/// <returns></returns>
public override Tuple<string, int, bool> ReadCode()
{
lock (readopLock)
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
for (int i = 0; i < MaxReadCount; i++)
{
bool flag = false;
//发送命令
if (!string.IsNullOrEmpty(configModel.Command))
{
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
providOrdinaryClient.SendCommand(command + Environment.NewLine);
}
else
{
providOrdinaryClient.SendCommand(command);
}
}
//开始允许接收
IsAllowReceive = true;
//记录开始的时间
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
//超过预定的时间跳出等待
break;
}
if (regex == null)
{
//直接拿过来
if (!string.IsNullOrEmpty(dataPack))
{
//只要有数据来就进来解析
datapack = dataPack;
var find = ErrorCodes.Find(o => o == datapack);
if (find == null)
{
isok = true;
}
}
}
else
{
var result = regex.Match(dataPack);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.Command.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => o == str);
if (find == null)
{
datapack = str;
isok = true;
}
}
}
if (isok)
{
//收到数据了
flag = true;
break;
}
//这个是为了破除最大线程数 防止死循环卡死的
Thread.Sleep(5);
}
if (flag)
{
//如果接收到了数据就跳出尝试循环
break;
}
}
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
//读取完成无论成功与否都结束接收
IsAllowReceive = false;
//清除缓存
dataPack = string.Empty;
IsBusy = false;
//这个时候拿出(返回)数据包
return Tuple.Create(datapack, vcode, isok);
}
}
public override void ReConnect()
{
providOrdinaryClient?.ReConnect();
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public override bool UnConnect()
{
if (providOrdinaryClient == null)
{
return false;
}
providOrdinaryClient.CloseConnect();
IsConnect = false;
return true;
}
/// <summary>
/// 原始数据接收
/// </summary>
/// <param name="data"></param>
/// <param name="encoding"></param>
private void RawData_Receive(byte[] data, Encoding encoding)
{
if (!IsAllowReceive)
{
return;
}
dataPack += encoding.GetString(data);
}
}
}

View File

@@ -0,0 +1,230 @@
using Keyence.AutoID.SDK;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_Keyence : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 基恩士扫码枪的读取器
/// </summary>
private ReaderAccessor reader { set; get; }
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
reader = new ReaderAccessor();
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
KeyenceConnectModel keyence = contentCache.GetContent<KeyenceConnectModel>(configModel.ProtocolKey);
if (keyence != null)
{
reader.CommandPort = reader.DataPort = keyence.Port;
}
oneEncoding = Encoding.ASCII;//sdk里写死的
return IsConnect = reader.Connect();
}
public override Tuple<string, int, bool> ReadCode()
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
for (int i = 0; i < MaxReadCount; i++)
{
var cmd = configModel.Command.Split('+')[0];
var code = reader.ExecCommand(cmd, configModel.OutTime);
if (regex == null)
{
var find = ErrorCodes.Find(o => o == code);
if (find == null)
{
datapack = code;
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
isok = true;
break;
}
}
else
{
var result = regex.Match(code);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.Command.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => o == str);
if (find == null)
{
datapack = str;
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
isok = true;
break;
}
}
}
}
IsBusy = false;
return Tuple.Create(datapack, vcode, isok);
}
public override void ReConnect()
{
if (!IsConnect)
{
reader.Connect();
}
}
public override bool UnConnect()
{
try
{
reader.Disconnect();
reader.Dispose();
return true;
}
catch (Exception)
{
return false;
}
}
}
}

View File

@@ -0,0 +1,304 @@
using StandardDomeNewApp.Communication.SerialPorts;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_SeriaPort : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 读取操作的锁
/// </summary>
private object readopLock { set; get; } = new object();
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 串口对象
/// </summary>
private SeriaPortController seriaPortController { set; get; }
/// <summary>
/// 一个串口的数据包 一个串口write有多个线程写都是会按照顺序写完一个包再写一个包的
/// </summary>
private string dataPack { set; get; }
/// <summary>
/// 是否允许开始接收了
/// </summary>
private bool IsAllowReceive { set; get; } = false;
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
/// <summary>
/// 建立对象
/// </summary>
/// <param name="config"></param>
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
seriaPortController = contentCache.GetContent<SeriaPortController>(configModel.ProtocolKey);
if (seriaPortController == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的串口对象!", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
seriaPortController.RawDataAction = RawData_Receive;
IsConnect = true;
oneEncoding = seriaPortController.encoding;
return true;
}
/// <summary>
/// 读取条码 (同步完成的)
/// </summary>
/// <returns></returns>
public override Tuple<string, int, bool> ReadCode()
{
lock (readopLock)
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
for (int i = 0; i < MaxReadCount; i++)
{
bool flag = false;
//发送命令
if (!string.IsNullOrEmpty(configModel.Command))
{
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
seriaPortController.Send(command + Environment.NewLine);
}
else
{
seriaPortController.Send(command);
}
}
//开始允许接收
IsAllowReceive = true;
//记录开始的时间
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
//超过预定的时间跳出等待
break;
}
if (regex == null)
{
//直接拿过来
if (!string.IsNullOrEmpty(dataPack))
{
//只要有数据来就进来解析
datapack = dataPack;
var find = ErrorCodes.Find(o => o == datapack);
if (find == null)
{
isok = true;
}
}
}
else
{
var result = regex.Match(dataPack);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.Command.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => o == str);
if (find == null)
{
datapack = str;
isok = true;
}
}
}
if (isok)
{
//收到数据了
flag = true;
break;
}
//这个是为了破除最大线程数 防止死循环卡死的
Thread.Sleep(5);
}
if (flag)
{
//如果接收到了数据就跳出尝试循环
break;
}
}
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
//读取完成无论成功与否都结束接收
IsAllowReceive = false;
//清除缓存
dataPack = string.Empty;
IsBusy = false;
//这个时候拿出(返回)数据包
return Tuple.Create(datapack, vcode, isok);
}
}
public override void ReConnect()
{
seriaPortController?.ReTryOpen();
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public override bool UnConnect()
{
if (seriaPortController == null)
{
return false;
}
seriaPortController.Close();
IsConnect = false;
return true;
}
/// <summary>
/// 原始数据接收
/// </summary>
/// <param name="data"></param>
/// <param name="encoding"></param>
private void RawData_Receive(byte[] data, Encoding encoding)
{
if (!IsAllowReceive)
{
return;
}
dataPack += encoding.GetString(data);
}
}
}

View File

@@ -0,0 +1,316 @@
using StandardDomeNewApp.Communication.Sockets;
using StandardDomeNewApp.Mappering;
using StandardDomeNewApp.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Communication.SweepCodeGun
{
public class ScanCode_ServerSocket : IScanCode
{
/// <summary>
/// 是否连接
/// </summary>
public override bool IsConnect
{
get => base.IsConnect;
protected set
{
if (base.IsConnect != value)
{
base.IsConnect = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.IsConnect = value ? 1 : 0;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 虚拟码
/// </summary>
public override int Vcode
{
get => base.Vcode;
set
{
if (base.Vcode != value)
{
base.Vcode = value;
if (configModel == null)
{
return;
}
using (var dbContext = new DataBaseMappering())
{
var find = dbContext.tbl_SweepCodeGunConfigs.Where(o => o.PrimaryKey == configModel.PrimaryKey);
if (find != null)
{
var list = find.ToList();
if (list.Count > 0)
{
var one = list.ElementAt(0);
//修改这个one
one.VCode = value;
dbContext.SaveChanges();
}
}
}
}
}
}
/// <summary>
/// 读取操作的锁
/// </summary>
private object readopLock { set; get; } = new object();
/// <summary>
/// 扫码枪配置参数
/// </summary>
private SweepCodeGunConfigModel configModel { set; get; }
/// <summary>
/// 服务对象
/// </summary>
private SingleSocketServer singleSocketServer { set; get; }
/// <summary>
/// 正则对象
/// </summary>
private Regex regex { set; get; }
public override void Build(object config)
{
if (config is SweepCodeGunConfigModel model)
{
configModel = model;
KeyName = configModel.PrimaryKey;
if (configModel.MaxVCode == -1 || configModel.MinVCode == -1)
{
IsUserVCode = false;
}
MaxVCode = configModel.MaxVCode;
MinVCode = configModel.MinVCode;
Vcode = configModel.VCode;
if (configModel.ErrorCode != null)
{
var errorcodes = configModel.ErrorCode.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in errorcodes)
{
ErrorCodes.Add(item);
}
}
if (!string.IsNullOrEmpty(configModel.CodeRegex))
{
regex = new Regex(configModel.CodeRegex);
}
}
}
public override bool Connect()
{
IsConnect = false;
if (configModel == null)
{
ShowMessageAction?.Invoke("请先Build后再尝试连接", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
singleSocketServer = contentCache.GetContent<SingleSocketServer>(configModel.ProtocolKey);
if (singleSocketServer == null)
{
ShowMessageAction?.Invoke($"无法找到[{configModel.ProtocolKey}]对应的串口对象!", false, Core.SysEnumInfon.MessageLogType.Info);
return false;
}
if (singleSocketServer.RequestReceivedAction == null)
{
singleSocketServer.RequestReceivedAction = RequestReceived;
}
if (singleSocketServer.OnSessionAccept == null)
{
singleSocketServer.OnSessionAccept = SessionAccept;
}
if (singleSocketServer.OnSessionClose == null)
{
singleSocketServer.OnSessionClose = SessionClose;
}
oneEncoding = singleSocketServer.encoding;
IsConnect = true;
return true;
}
public override Tuple<string, int, bool> ReadCode()
{
lock (readopLock)
{
IsBusy = true;
string datapack = "";
int vcode = -1;
bool isok = false;
var id = singleSocketServer.GetSessionID(configModel.Reserve);
for (int i = 0; i < MaxReadCount; i++)
{
bool flag = false;
//发送命令
if (!string.IsNullOrEmpty(configModel.Command))
{
var array = configModel.Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
singleSocketServer.SessionSend(command + Environment.NewLine, id);
}
else
{
singleSocketServer.SessionSend(command, id);
}
}
//开始允许接收
singleSocketServer.IsAllowReceiveDic[id] = true;
//记录开始的时间
DateTime dateTime = DateTime.Now;
while (true)
{
if ((DateTime.Now - dateTime).TotalMilliseconds > configModel.OutTime)
{
//超过预定的时间跳出等待
break;
}
if (regex == null)
{
//直接拿过来
if (!string.IsNullOrEmpty(singleSocketServer.SessionDataDic[id]))
{
//只要有数据来就进来解析
datapack = singleSocketServer.SessionDataDic[id];
var find = ErrorCodes.Find(o => o == datapack);
if (find == null)
{
isok = true;
}
}
}
else
{
var result = regex.Match(singleSocketServer.SessionDataDic[id]);
if (result.Success)
{
//去头去尾
string str = result.Value;
var arrayconnand = configModel.Command.Split(new string[] { ".*" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrayconnand)
{
str = str.Replace(item, "");
}
var find = ErrorCodes.Find(o => o == str);
if (find == null)
{
datapack = str;
isok = true;
}
}
}
if (isok)
{
//收到数据了
flag = true;
break;
}
//这个是为了破除最大线程数 防止死循环卡死的
Thread.Sleep(5);
}
if (flag)
{
//如果接收到了数据就跳出尝试循环
break;
}
}
if (IsUserVCode)
{
Vcode++;
if (Vcode > MaxVCode)
{
Vcode = MinVCode;
}
vcode = Vcode;
}
//读取完成无论成功与否都结束接收
singleSocketServer.IsAllowReceiveDic[id] = false;
//清除缓存
singleSocketServer.SessionDataDic[id] = string.Empty;
IsBusy = false;
//这个时候拿出(返回)数据包
return Tuple.Create(datapack, vcode, isok);
}
}
public override void ReConnect()
{
//服务不需要
}
public override bool UnConnect()
{
if (singleSocketServer == null)
{
return false;
}
singleSocketServer.StopServer();
IsConnect = false;
return true;
}
private void RequestReceived(string id, string data)
{
if (singleSocketServer.IsAllowReceiveDic.ContainsKey(id))
{
if (!singleSocketServer.IsAllowReceiveDic[id])
{
//其中一个会话返回
return;
}
if (singleSocketServer.SessionDataDic.ContainsKey(id))
{
singleSocketServer.SessionDataDic[id] += data;
}
}
}
private void SessionAccept(string id)
{
singleSocketServer.IsAllowReceiveDic[id] = false;
singleSocketServer.SessionDataDic[id] = string.Empty;
}
private void SessionClose(string id)
{
if (singleSocketServer.SessionDataDic.ContainsKey(id))
{
singleSocketServer.SessionDataDic.TryRemove(id, out string str);
}
if (singleSocketServer.IsAllowReceiveDic.ContainsKey(id))
{
singleSocketServer.IsAllowReceiveDic.TryRemove(id, out bool state);
}
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StandardDomeNewApp.Enums
{
public class CowainEnum
{
public enum DatabaseType
{
SQLModel,
MySQLModel
}
public enum Language
{
English,
Chinese
}
public enum LogLevel
{
OFF,
FATAL,
ERROR,
WARN,
INFO,
DEBUG,
ALL,
OPERATE,
}
public enum ParaType
{
Temperature,
Anemometer,
Vacuum,
Weight,
Energy,//addw
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 303 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 477 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 840 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 759 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 963 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 995 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1008 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 877 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 845 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 742 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 790 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 783 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 860 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 914 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 761 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Some files were not shown because too many files have changed in this diff Show More