首次上传

This commit is contained in:
hanqiangqiang
2026-06-15 10:56:30 +08:00
commit b0213b94d6
4160 changed files with 736101 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,85 @@
<UserControl x:Class="MECF.Framework.Simulator.Core.Commons.CommonSerialPortDeviceSimulatorView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MECF.Framework.Simulator.Core.Commons"
mc:Ignorable="d"
xmlns:commons="clr-namespace:MECF.Framework.Simulator.Core.Commons"
Height="900" Width="1800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="300"></RowDefinition>
<RowDefinition Height="350"></RowDefinition>
</Grid.RowDefinitions>
<commons:SocketTitleView Grid.Row="0"></commons:SocketTitleView>
<Canvas Grid.Row="1" Width="750">
<CheckBox Content="Auto-Reply" IsChecked="{Binding AutoReply}" Canvas.Left="36" Canvas.Top="15"></CheckBox>
<CheckBox Content="Fail" IsChecked="{Binding IsFailed}" Canvas.Left="156" Canvas.Top="15"></CheckBox>
<Button Content="Clear Log" Width="80" Height="25" Command="{Binding ClearLogCommand}" Canvas.Left="600" Canvas.Top="10"></Button>
</Canvas>
<DataGrid x:Name="_simaulatorItemGrid" CanUserAddRows="False" ItemsSource="{Binding IOSimulatorItemViewModelConfig.IOSimulatorItemList}" Grid.Row="2" AutoGenerateColumns="False" SelectionMode="Single" >
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTipService.ToolTip" Value="{Binding RelativeSource={RelativeSource Mode=Self},Path=Content.Text}" />
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Command" Width="250" Binding="{Binding SourceCommandName, Mode=OneWay}"/>
<DataGridTextColumn Header="Content" Width="*" Binding="{Binding CommandContent, Mode=OneWay}"/>
<DataGridTextColumn Header="Recieved Time" Width="200" Binding="{Binding CommandRecievedTime, Mode=OneWay}"/>
<DataGridTextColumn Header="Resonse" Width="500" Binding="{Binding Response, UpdateSourceTrigger=LostFocus, Mode=TwoWay}"/>
<DataGridTemplateColumn Header="Manual Reply" Width="150">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="BtnReply" Content="Reply" Height="20"
Width="50" Click="BtnReply_Click" IsEnabled="{Binding IsManualReplyEnable}"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<!--IsEnabled="{Binding IsManualReplyEnable}"-->
<DataGrid Grid.Row="3" FontSize="16" AutoGenerateColumns="False" CanUserAddRows="False" CanUserResizeRows="False" CanUserSortColumns="False" ItemsSource="{Binding TransactionLogItems}"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
Width="1800" Height="320" VerticalAlignment="Top">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Width="160" IsReadOnly="True" Binding="{Binding OccurTime, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Incoming" Width="810" IsReadOnly="True" Binding="{Binding Incoming, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Height" Value="auto"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Outgoing" Width="810" IsReadOnly="True" Binding="{Binding Outgoing, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Height" Value="auto"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</UserControl>
@@ -0,0 +1,153 @@
using Aitex.Core.RT.Device;
using Aitex.Core.Utilities;
using MECF.Framework.Simulator.Core.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MECF.Framework.Simulator.Core.Commons
{
/// <summary>
/// SiasunPhoenixBSimulatorView.xaml 的交互逻辑
/// </summary>
public partial class CommonSerialPortDeviceSimulatorView : UserControl
{
CommonSerialPortSimulatorViewModel _viewModel;
public CommonSerialPortDeviceSimulatorView()
{
InitializeComponent();
}
public void Initialize(string deviceGroup, string deviceName, string defaultPort, bool isNewVersion = false)
{
_viewModel = new CommonSerialPortSimulatorViewModel(deviceGroup, deviceName, defaultPort, isNewVersion);
_viewModel.SerialIOSimulator.SimulatorItemActived += SerialIOReader_SimulatorItemActived;
this.DataContext = _viewModel;
this.Loaded += CommonSerialPortDeviceSimulatorView_Loaded;
}
private void SerialIOReader_SimulatorItemActived(IOSimulatorItemViewModel obj)
{
this.Dispatcher.Invoke(new Action(() =>
{
_simaulatorItemGrid.SelectedItem = obj;
}));
}
private void CommonSerialPortDeviceSimulatorView_Loaded(object sender, RoutedEventArgs e)
{
_viewModel.EnableTimer(true);
}
private void BtnReply_Click(object sender, RoutedEventArgs e)
{
IOSimulatorItemViewModel commandViewModel = (IOSimulatorItemViewModel)_simaulatorItemGrid.SelectedItem;
if (commandViewModel != null)
{
_viewModel.SerialIOSimulator.ManualWriteMessage(commandViewModel);
}
}
}
class CommonSerialPortSimulatorViewModel : SerialPortDeviceViewModel
{
public CommonSerialPortSimulatorViewModel(string deviceGroup, string deviceName, string port, bool isNewVersion) : base("CommonSerialPortSimulatorViewModel")
{
SerialIOSimulator = SerialPortDeviceSimulatorFactory.GetCommonSerialPortDeviceSimulator(port, deviceName);
Init(SerialIOSimulator,true);
_deviceName = deviceName;
if (isNewVersion)
IOSimulatorItemViewModelConfig = IOSimulatorItemReader.GetCommandModelConfigV2(deviceName);
else
IOSimulatorItemViewModelConfig = IOSimulatorItemReader.GetCommandModelConfig(deviceGroup, deviceName);
IOSimulatorItemViewModelConfig.IOSimulatorItemList.ForEach(sItem =>
{
sItem.IsManualReplyEnable = !AutoReply;
sItem.Response = IsFailed ? sItem.FailedResponseStr : sItem.SuccessResponseStr;
});
SerialIOSimulator.IOSimulatorItemList = IOSimulatorItemViewModelConfig.IOSimulatorItemList;
}
private string _deviceName;
public IOSimulatorItemViewModelConfig IOSimulatorItemViewModelConfig { get; set; }
public string Title
{
get { return _deviceName + " Simulator"; }
}
public CommonSerialPortDeviceSimulator SerialIOSimulator;
public bool IsFailed
{
get
{
return SerialIOSimulator.Failed;
}
set
{
SerialIOSimulator.Failed = value;
IOSimulatorItemViewModelConfig.IOSimulatorItemList.ForEach(sItem =>
{
sItem.Response = value ? sItem.FailedResponseStr : sItem.SuccessResponseStr;
});
}
}
public bool AutoReply
{
get
{
return SerialIOSimulator.AutoReply;
}
set
{
SerialIOSimulator.AutoReply = value;
IOSimulatorItemViewModelConfig.IOSimulatorItemList.ForEach(sItem =>
{
sItem.IsManualReplyEnable = !value;
});
}
}
//private string _value;
[IgnorePropertyChange]
public string ResultValue
{
get
{
return SerialIOSimulator.ResultValue;
}
set
{
SerialIOSimulator.ResultValue = value;
}
}
}
}
@@ -0,0 +1,325 @@
using MECF.Framework.Simulator.Core.Commons;
using MECF.Framework.Simulator.Core.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
namespace MECF.Framework.Simulator.Core.Commons
{
public class SocketDeviceSimulatoFactory
{
public static CommonSocketDeviceSimulator GetCommonSocketDeviceSimulator(int port, string deviceName)
{
if (deviceName == "Hanbell")
{
return new HanbellPumpSocketSimulator(port, deviceName);
}
else if (deviceName == "SiasunPhoenixB")
{
return new SiasunPhoenixBSocketSimulator(port, deviceName);
}
else if (deviceName == "Siasun1500C800C")
{
return new Siasun1500C800CSocketSimulator(port, deviceName);
}
return null;
}
}
public class CommonSocketDeviceSimulator : SimpleSocketDeviceSimulator
{
public bool Failed { get; set; }
public bool AutoReply { get; set; } = true;
public bool IsAtSpeed { get; set; }
Stopwatch _timer = new Stopwatch();
private System.Timers.Timer _tick;
private object _locker = new object();
public string ResultValue { get; set; }
public List<IOSimulatorItemViewModel> IOSimulatorItemList { get; set; }
public event Action<IOSimulatorItemViewModel> SimulatorItemActived;
string _deviceName;
public CommonSocketDeviceSimulator(int port, string deviceName, bool isAscii = true, string newLine = "\r")
: base(port, -1, newLine, ',', isAscii)
{
_deviceName = deviceName;
ResultValue = "";
_tick = new System.Timers.Timer();
_tick.Interval = 200;
_tick.Elapsed += _tick_Elapsed;
_tick.Start();
IsAtSpeed = true;
}
private void _tick_Elapsed(object sender, ElapsedEventArgs e)
{
lock (_locker)
{
if (_timer.IsRunning && _timer.Elapsed > TimeSpan.FromSeconds(10))
{
_timer.Stop();
IsAtSpeed = true;
}
}
}
protected override void ProcessUnsplitMessage(byte[] binaryMessage)
{
lock (_locker)
{
var activeSimulatorItem = GetActiveIOSimulatorItemViewModel(binaryMessage);
if (activeSimulatorItem == null) return;
activeSimulatorItem.CommandContent = string.Join(",", binaryMessage.Select(bt => bt.ToString("X2")).ToArray());
activeSimulatorItem.CommandRecievedTime = DateTime.Now;
if (SimulatorItemActived != null)
SimulatorItemActived(activeSimulatorItem);
if (AutoReply)
{
OnWriteSimulatorItem(activeSimulatorItem);
}
}
}
protected override void ProcessUnsplitMessage(string msg)
{
lock (_locker)
{
var activeSimulatorItem = GetActiveIOSimulatorItemViewModel(msg);
if (activeSimulatorItem == null) return;
activeSimulatorItem.CommandContent = msg;
activeSimulatorItem.CommandRecievedTime = DateTime.Now;
if (SimulatorItemActived != null)
SimulatorItemActived(activeSimulatorItem);
if (AutoReply)
{
OnWriteSimulatorItem(activeSimulatorItem);
}
}
}
protected virtual IOSimulatorItemViewModel GetActiveIOSimulatorItemViewModel(string msg)
{
return null;
}
protected virtual IOSimulatorItemViewModel GetActiveIOSimulatorItemViewModel(byte[] msg)
{
return null;
}
protected virtual void OnWriteSimulatorItem(IOSimulatorItemViewModel activeSimulatorItem)
{
}
public void ManualWriteMessage(IOSimulatorItemViewModel activeSimulatorItem)
{
OnWriteSimulatorItem(activeSimulatorItem);
}
}
public class SiasunPhoenixBSocketSimulator : CommonSocketDeviceSimulator
{
private bool _isWaferPresent = false;
private string _endline = "\r\n";
private readonly Dictionary<string, int> _timeConfigs = new Dictionary<string, int>();
public SiasunPhoenixBSocketSimulator(int port, string deviceName) : base(port, deviceName)
{
//try
//{
// Hashtable timeSim = (Hashtable)ConfigurationManager.GetSection("VacRobotSim");
// _timeConfigs.Add("PICK", int.Parse(timeSim["PICK"].ToString()) * 1000);
// _timeConfigs.Add("PLACE", int.Parse(timeSim["PLACE"].ToString()) * 1000);
// _timeConfigs.Add("GOTO", int.Parse(timeSim["GOTO"].ToString()) * 1000);
// _timeConfigs.Add("RQLOAD", int.Parse(timeSim["RQLOAD"].ToString()) * 1000);
// _timeConfigs.Add("CHECKLOAD", int.Parse(timeSim["CHECKLOAD"].ToString()) * 1000);
// _timeConfigs.Add("HOME", int.Parse(timeSim["HOME"].ToString()) * 1000);
//}
//catch (ConfigurationErrorsException ex)
//{
// throw ex;
//}
}
protected override IOSimulatorItemViewModel GetActiveIOSimulatorItemViewModel(string msg)
{
if (IOSimulatorItemList == null)
return null;
foreach (var simulatorItem in IOSimulatorItemList)
{
if (msg.Contains(simulatorItem.SourceCommandName))
{
return simulatorItem;
}
}
return null;
}
protected override void OnWriteSimulatorItem(IOSimulatorItemViewModel activeItem)
{
string cmdName = activeItem.SourceCommandName;
if (cmdName.StartsWith("RQ"))
{
if (cmdName.StartsWith("RQ LOAD"))
{
//Thread.Sleep(_timeConfigs["RQLOAD"]);
string response = $"{activeItem.Response} {(activeItem.CommandContent.Contains(" A") ? "A" : "B")} {(_isWaferPresent ? "ON" : "OFF")}";
OnWriteMessage(response + _endline + "_RDY" + _endline);
}
else
{
OnWriteMessage(activeItem.Response + _endline + "_RDY" + _endline);
}
//OnWriteMessage("_RDY" + _endline);
return;
}
else if (cmdName.StartsWith("CHECK LOAD"))
{
Thread.Sleep(1000);
}
else if (cmdName.StartsWith("HOME"))
{
Thread.Sleep(2000);
}
else if (cmdName.StartsWith("RESET"))
{
return;
}
else if (cmdName.StartsWith("PICK"))
{
Thread.Sleep(2000);
}
else if (cmdName.StartsWith("PLACE"))
{
Thread.Sleep(2000);
}
else if (cmdName.StartsWith("GOTO"))
{
Thread.Sleep(1500);
}
OnWriteMessage(activeItem.Response + _endline);
}
}
public class Siasun1500C800CSocketSimulator : CommonSocketDeviceSimulator
{
public Siasun1500C800CSocketSimulator(int port, string deviceName) : base(port, deviceName)
{
}
protected override IOSimulatorItemViewModel GetActiveIOSimulatorItemViewModel(string msg)
{
if (IOSimulatorItemList == null)
return null;
foreach (var simulatorItem in IOSimulatorItemList)
{
if (msg.Contains(simulatorItem.SourceCommandName))
{
return simulatorItem;
}
}
return null;
}
protected override void OnWriteSimulatorItem(IOSimulatorItemViewModel activeSimulatorItem)
{
if (activeSimulatorItem.SourceCommandName.StartsWith("RQ"))
{
OnWriteMessage(activeSimulatorItem.Response + "\r");
Thread.Sleep(1000);
OnWriteMessage("_RDY" + "\r");
}
else
{
OnWriteMessage(activeSimulatorItem.Response + "\r");
}
}
}
internal class HanbellPumpSocketSimulator : CommonSocketDeviceSimulator
{
private List<byte> _msgBuffer = new List<byte>();
private bool _isPumpOn;
private List<byte> statusArray;
public HanbellPumpSocketSimulator(int port, string deviceName) : base(port, deviceName, false)
{
statusArray = Enumerable.Repeat((byte)0x0,90).ToList();
}
protected override IOSimulatorItemViewModel GetActiveIOSimulatorItemViewModel(byte[] msg)
{
if (IOSimulatorItemList == null)
return null;
_msgBuffer.AddRange(msg);
if (_msgBuffer.Count < 12)
{
return null;
}
foreach (var simulatorItem in IOSimulatorItemList)
{
if (msg[7] == byte.Parse(simulatorItem.SourceCommand))
{
//action
if (msg[7] == 5)
{
simulatorItem.Response = string.Join(",", msg.Take(12).Select(bt => bt.ToString("X2")).ToArray());
}
_msgBuffer.RemoveRange(0, 12);
return simulatorItem;
}
}
return null;
}
protected override void OnWriteSimulatorItem(IOSimulatorItemViewModel activeSimulatorItem)
{
var responseArray = activeSimulatorItem.Response.Split(',').Select(s => Convert.ToByte(s, 16)).ToArray();
if(activeSimulatorItem.SourceCommandName == "OperatePump")
{
var response = activeSimulatorItem.Response.Split(',').Select(s => Convert.ToByte(s, 16)).ToArray();
_isPumpOn = response[10] == 0xFF;
OnWriteMessage(response);
}
if (activeSimulatorItem.SourceCommandName == "RequestRegisters")
{
List<byte> buffer = new List<byte>();
buffer.AddRange(activeSimulatorItem.Response.Split(',').Select(s => Convert.ToByte(s, 16)).ToArray());
statusArray[61] = (byte)(_isPumpOn ? 0xdc : 0x7f);
buffer.AddRange(statusArray);
OnWriteMessage(buffer.ToArray());
}
}
}
}
@@ -0,0 +1,84 @@
<UserControl x:Class="MECF.Framework.Simulator.Core.Commons.CommonSocketDeviceSimulatorView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MECF.Framework.Simulator.Core.Commons"
mc:Ignorable="d"
xmlns:commons="clr-namespace:MECF.Framework.Simulator.Core.Commons"
Height="900" Width="750">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="350"></RowDefinition>
<RowDefinition Height="300"></RowDefinition>
</Grid.RowDefinitions>
<commons:SocketTitleView Grid.Row="0"></commons:SocketTitleView>
<Canvas Grid.Row="1" Width="750">
<CheckBox Content="Auto-Reply" IsChecked="{Binding AutoReply}" Canvas.Left="36" Canvas.Top="15"></CheckBox>
<CheckBox Content="Fail" IsChecked="{Binding IsFailed}" Canvas.Left="156" Canvas.Top="15"></CheckBox>
<Button Content="Clear Log" Width="80" Height="25" Command="{Binding ClearLogCommand}" Canvas.Left="600" Canvas.Top="10"></Button>
</Canvas>
<DataGrid x:Name="_simaulatorItemGrid" CanUserAddRows="False" ItemsSource="{Binding IOSimulatorItemViewModelConfig.IOSimulatorItemList}" Grid.Row="2" AutoGenerateColumns="False" SelectionMode="Single" >
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTipService.ToolTip" Value="{Binding RelativeSource={RelativeSource Mode=Self},Path=Content.Text}" />
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Command" Width="80" Binding="{Binding SourceCommandName, Mode=OneWay}"/>
<DataGridTextColumn Header="Content" Width="*" Binding="{Binding CommandContent, Mode=OneWay}"/>
<DataGridTextColumn Header="Recieved Time" Width="120" Binding="{Binding CommandRecievedTime, Mode=OneWay}"/>
<DataGridTextColumn Header="Resonse" Width="150" Binding="{Binding Response, UpdateSourceTrigger=LostFocus, Mode=TwoWay}"/>
<DataGridTemplateColumn Header="Manual Reply" Width="80">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="BtnReply" Content="Reply" Height="20"
Width="50" Click="BtnReply_Click" IsEnabled="{Binding IsManualReplyEnable}"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<!--IsEnabled="{Binding IsManualReplyEnable}"-->
<DataGrid Grid.Row="3" FontSize="16" AutoGenerateColumns="False" CanUserAddRows="False" CanUserResizeRows="False" CanUserSortColumns="False" ItemsSource="{Binding TransactionLogItems}"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto" Height="380" VerticalAlignment="Top" Margin="0,0,0,-79">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Width="160" IsReadOnly="True" Binding="{Binding OccurTime, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Incoming" Width="350" IsReadOnly="True" Binding="{Binding Incoming, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Height" Value="auto"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Outgoing" Width="350" IsReadOnly="True" Binding="{Binding Outgoing, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Height" Value="auto"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</UserControl>
@@ -0,0 +1,145 @@
using Aitex.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MECF.Framework.Simulator.Core.Commons
{
/// <summary>
/// CommonSocketDeviceSimulatorView.xaml 的交互逻辑
/// </summary>
public partial class CommonSocketDeviceSimulatorView : UserControl
{
CommonSocketSimulatorViewModel _viewModel;
public void Initialize(string deviceGroup, string deviceName, int defaultPort)
{
_viewModel = new CommonSocketSimulatorViewModel(deviceGroup, deviceName, defaultPort);
_viewModel.SerialIOSimulator.SimulatorItemActived += SerialIOReader_SimulatorItemActived;
this.DataContext = _viewModel;
this.Loaded += SiasunPhoenixBSimulatorView_Loaded;
}
public CommonSocketDeviceSimulatorView()
{
InitializeComponent();
}
private void SerialIOReader_SimulatorItemActived(IOSimulatorItemViewModel obj)
{
this.Dispatcher.Invoke(new Action(() =>
{
_simaulatorItemGrid.SelectedItem = obj;
}));
}
private void SiasunPhoenixBSimulatorView_Loaded(object sender, RoutedEventArgs e)
{
_viewModel.EnableTimer(true);
}
private void BtnReply_Click(object sender, RoutedEventArgs e)
{
IOSimulatorItemViewModel commandViewModel = (IOSimulatorItemViewModel)_simaulatorItemGrid.SelectedItem;
if (commandViewModel != null)
{
_viewModel.SerialIOSimulator.ManualWriteMessage(commandViewModel);
}
}
}
class CommonSocketSimulatorViewModel : SimpleSocketDeviceViewModel
{
public CommonSocketSimulatorViewModel(string deviceGroup, string deviceName, int port) : base("CommonSocketSimulatorViewModel")
{
SerialIOSimulator = SocketDeviceSimulatoFactory.GetCommonSocketDeviceSimulator(port, deviceName);
Init(SerialIOSimulator, true);
_deviceName = deviceName;
//IOSimulatorItemViewModelConfig = IOSimulatorItemReader.GetCommandModelConfig(deviceGroup, deviceName);
IOSimulatorItemViewModelConfig = IOSimulatorItemReader.GetCommandModelConfigV2(deviceName);
IOSimulatorItemViewModelConfig.IOSimulatorItemList.ForEach(sItem =>
{
sItem.IsManualReplyEnable = !AutoReply;
sItem.Response = IsFailed ? sItem.FailedResponseStr : sItem.SuccessResponseStr;
});
SerialIOSimulator.IOSimulatorItemList = IOSimulatorItemViewModelConfig.IOSimulatorItemList;
}
private string _deviceName;
public IOSimulatorItemViewModelConfig IOSimulatorItemViewModelConfig { get; set; }
public string Title
{
get { return _deviceName + " Simulator"; }
}
public CommonSocketDeviceSimulator SerialIOSimulator;
public bool IsFailed
{
get
{
return SerialIOSimulator.Failed;
}
set
{
SerialIOSimulator.Failed = value;
IOSimulatorItemViewModelConfig.IOSimulatorItemList.ForEach(sItem =>
{
sItem.Response = value ? sItem.FailedResponseStr : sItem.SuccessResponseStr;
});
}
}
public bool AutoReply
{
get
{
return SerialIOSimulator.AutoReply;
}
set
{
SerialIOSimulator.AutoReply = value;
IOSimulatorItemViewModelConfig.IOSimulatorItemList.ForEach(sItem =>
{
sItem.IsManualReplyEnable = !value;
});
}
}
//private string _value;
[IgnorePropertyChange]
public string ResultValue
{
get
{
return SerialIOSimulator.ResultValue;
}
set
{
SerialIOSimulator.ResultValue = value;
}
}
}
}
@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MECF.Framework.Simulator.Core.Driver
{
public class DeviceSimulator
{
public event Action<string> MessageIn;
public event Action<string> MessageOut;
public event Action<string> ErrorOccur;
public virtual bool IsEnabled => false;
public virtual bool IsConnected => false;
protected SortedList<string, Action<string>> commandList = new SortedList<string, Action<string>>();
protected string _lineDelimiter;
protected char _msgDelimiter;
protected int _commandIndex;
protected int _cmdMaxLength = 4;
public DeviceSimulator(int commandIndex, string lindDelimiter, char msgDelimiter, int cmdMaxLength=4)
{
_lineDelimiter = lindDelimiter;
_msgDelimiter = msgDelimiter;
_commandIndex = commandIndex;
_cmdMaxLength = cmdMaxLength;
}
protected virtual void AddCommandHandler(string command, Action<string> handler)
{
commandList.Add(command, handler);
}
protected virtual void ProcessUnsplitMessage(string message)
{
}
protected virtual void ProcessUnsplitMessage(byte[] message)
{
}
protected virtual void OnErrorMessage(string message)
{
if (ErrorOccur != null)
{
ErrorOccur(message);
}
}
protected void OnReadMessage(byte[] message)
{
if (MessageIn != null)
{
MessageIn(string.Join(" ", Array.ConvertAll(message, x=>x.ToString("X2"))));
MessageIn(Encoding.ASCII.GetString(message));
}
// liuyao : 这里好像有点什么问题,如果发byte会不行,我也忘记了
//OnReadMessage(Encoding.ASCII.GetString(message));
ProcessUnsplitMessage(message);
}
protected void OnReadMessage(string message)
{
if (MessageIn != null)
{
MessageIn(message);
}
if (_commandIndex < 0)
{
ProcessUnsplitMessage(message);
return;
}
if (_msgDelimiter.Equals(' '))
{
string cmd = message.Contains(_msgDelimiter)? message.Substring(_commandIndex, _cmdMaxLength):message;
//string cmd = message.Substring(_commandIndex, _cmdMaxLength);
if (cmd.Contains(_msgDelimiter))
cmd = cmd.Substring(0, cmd.IndexOf(_msgDelimiter));
if (!commandList.ContainsKey(cmd))
{
CommandNotRecognized(message);
}
else
{
//Log.WriteIfEnabled( LogCategory.Debug, source, DeviceId + ":ProcessMessages: '" + msg.Message );
var handler = commandList[cmd];
if (handler == null)
{
//Log.WriteIfEnabled( LogCategory.Error, source, DeviceId + ":ProcessMessages: CANNOT FIND MESSAGE HANDLER '" + msg.Message );
}
else
{
if (!message.Contains("stat_pdo") && !message.Contains("statfx"))
{
//Log.WriteIfEnabled(LogCategory.Debug, source, "Received command " + message);
}
handler(message);
}
}
}
else
{
string[] msgComponents = message.Split(_msgDelimiter);
int index = msgComponents[0] == "$$$" ? 1 : _commandIndex;
if (msgComponents.Length <= index)
{
CommandNotRecognized(message);
return;
}
// find the message handler in the dictionary
string cmd = msgComponents[index];
if (!commandList.ContainsKey(cmd))
{
CommandNotRecognized(message);
}
else
{
//Log.WriteIfEnabled( LogCategory.Debug, source, DeviceId + ":ProcessMessages: '" + msg.Message );
var handler = commandList[cmd];
if (handler == null)
{
//Log.WriteIfEnabled( LogCategory.Error, source, DeviceId + ":ProcessMessages: CANNOT FIND MESSAGE HANDLER '" + msg.Message );
}
else
{
if (!message.Contains("stat_pdo") && !message.Contains("statfx"))
{
//Log.WriteIfEnabled(LogCategory.Debug, source, "Received command " + message);
}
handler(message);
}
}
}
}
protected virtual void CommandNotRecognized(string msg)
{
if (commandList.ContainsKey("Unknown") && commandList["Unknown"] != null)
{
commandList["Unknown"](msg);
}
else
{
ProcessWriteMessage("_ERR Unrecognized command");
}
}
protected void OnWriteMessage(string msg)
{
if (MessageOut != null)
MessageOut(msg);
ProcessWriteMessage(msg);
}
protected void OnWriteMessage(byte[] msg)
{
if (MessageOut != null)
MessageOut(string.Join(" ", Array.ConvertAll(msg, x => x.ToString("X2"))));
ProcessWriteMessage(msg);
}
protected virtual void ProcessWriteMessage(string msg)
{
}
protected virtual void ProcessWriteMessage(byte[] msg)
{
}
}
}
@@ -0,0 +1,59 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MECF.Framework.Simulator.Core.Commons
{
public class IOSimulatorItemReader
{
private static Dictionary<string, IOSimulatorItemViewModelConfig> _commandModelConfigDict = new Dictionary<string, IOSimulatorItemViewModelConfig>();
public static IOSimulatorItemViewModelConfig GetCommandModelConfig(string hardwarePath, string hardwareName)
{
IOSimulatorItemViewModelConfig commandModelConfig = null;
if (_commandModelConfigDict.Keys.Contains(hardwareName))
{
commandModelConfig = _commandModelConfigDict[hardwareName];
}
else
{
commandModelConfig = JsonConvert.DeserializeObject<IOSimulatorItemViewModelConfig>(File.ReadAllText(ConfigPath.AssemblyPath + $"\\{hardwarePath}\\{hardwareName}\\IOSimulatorItems.json"));
_commandModelConfigDict.Add(hardwareName, commandModelConfig);
}
return commandModelConfig;
}
public static IOSimulatorItemViewModelConfig GetCommandModelConfigV2(string hardwareName)
{
IOSimulatorItemViewModelConfig commandModelConfig = null;
if (_commandModelConfigDict.Keys.Contains(hardwareName))
{
commandModelConfig = _commandModelConfigDict[hardwareName];
}
else
{
commandModelConfig = JsonConvert.DeserializeObject<IOSimulatorItemViewModelConfig>(File.ReadAllText(ConfigPath.AssemblyPath + $"\\SimulatorItems\\{hardwareName}_IOSimulatorItems.json"));
_commandModelConfigDict.Add(hardwareName, commandModelConfig);
}
return commandModelConfig;
}
}
public class ConfigPath
{
public static string AssemblyPath
{
get
{
string path = Assembly.GetExecutingAssembly().Location;
FileInfo finfo = new FileInfo(path);
return finfo.DirectoryName;
}
}
}
}
@@ -0,0 +1,113 @@
using Aitex.Core.UI.MVVM;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MECF.Framework.Simulator.Core.Commons
{
public class IOSimulatorItemViewModel: ViewModelBase
{
public string SourceCommandName { get; set; }//key
public string SourceCommand { get; set; }
public string SourceCommandType { get; set; }
private string _commandContent;
public string CommandContent
{
get { return _commandContent; }
set
{
_commandContent = value;
InvokePropertyChanged("CommandContent");
}
}
private DateTime _commandRecievedTime;
public DateTime CommandRecievedTime
{
get { return _commandRecievedTime; }
set
{
_commandRecievedTime = value;
InvokePropertyChanged("CommandRecievedTime");
}
}
private string _response;
public string Response
{
get { return _response; }
set
{
_response = value;
InvokePropertyChanged("Response");
}
}
public string SuccessResponseStr
{
get
{
if(SuccessResponse != null)
{
var sResponse = SuccessResponse.ToString();
if (sResponse.Contains('{'))
{
return JsonConvert.SerializeObject(SuccessResponse);
}
else
{
return sResponse;
}
}
return null;
}
}
public string FailedResponseStr
{
get
{
if(FailedResponse != null)
{
var sResponse = FailedResponse.ToString();
if (sResponse.Contains('{'))
{
return JsonConvert.SerializeObject(FailedResponse);
}
else
{
return sResponse;
}
}
return null;
}
}
public object SuccessResponse { get; set; }//value, as default response
public object FailedResponse { get; set; }//value, as default response
//public int AutoReplyTimeout { get; set; }
private bool _isManualReplyEnable;
public bool IsManualReplyEnable
{
get { return _isManualReplyEnable; }
set {
_isManualReplyEnable = value;
InvokePropertyChanged("IsManualReplyEnable");
}
}
}
public class IOSimulatorItemViewModelConfig
{
public List<IOSimulatorItemViewModel> IOSimulatorItemList { get; set; }
}
}
@@ -0,0 +1,98 @@
using System.IO.Ports;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.Simulator.Core.Driver
{
public class SerialPortDeviceSimulator : DeviceSimulator
{
#region Variables
private readonly AsyncSerialPort _serialPort;
#endregion
#region Constructors
public SerialPortDeviceSimulator(string port, int commandIndex, string lineDelimiter, char msgDelimiter,
bool isAscii = true)
: base(commandIndex, lineDelimiter, msgDelimiter)
{
_serialPort = new AsyncSerialPort(port, 9600, 8, Parity.None, StopBits.One, lineDelimiter, isAscii);
_serialPort.OnDataChanged += OnReadMessage;
_serialPort.OnBinaryDataChanged += OnReadMessage;
_serialPort.OnErrorHappened += OnErrorMessage;
}
public SerialPortDeviceSimulator(string port, int commandIndex, string lineDelimiter, char msgDelimiter,
bool isAscii, int dataBits)
: base(commandIndex, lineDelimiter, msgDelimiter)
{
_serialPort = new AsyncSerialPort(port, 19200, dataBits, Parity.Even, StopBits.One, lineDelimiter, isAscii);
_serialPort.OnDataChanged += OnReadMessage;
_serialPort.OnBinaryDataChanged += OnReadMessage;
_serialPort.OnErrorHappened += OnErrorMessage;
}
public SerialPortDeviceSimulator(string port, int commandIndex, string lineDelimiter, char msgDelimiter,
bool isAscii, string parity)
: base(commandIndex, lineDelimiter, msgDelimiter)
{
_serialPort = new AsyncSerialPort(port, 9600, 8, Parity.Even, StopBits.One, lineDelimiter, isAscii);
_serialPort.OnDataChanged += OnReadMessage;
_serialPort.OnBinaryDataChanged += OnReadMessage;
_serialPort.OnErrorHappened += OnErrorMessage;
}
#endregion
#region Properties
public override bool IsEnabled => _serialPort != null && _serialPort.IsOpen();
public override bool IsConnected => IsEnabled;
public string PortName
{
get => _serialPort.PortName;
set => _serialPort.PortName = value;
}
public string RemoteConnection { get; set; }
#endregion
#region Methods
public void Enable()
{
_serialPort.Open();
}
public void Disable()
{
_serialPort.Close();
}
protected override void ProcessWriteMessage(string msg)
{
_serialPort.Write(msg);
}
protected override void ProcessWriteMessage(byte[] msg)
{
_serialPort.Write(msg);
}
#endregion
}
}
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Windows;
using System.Windows.Input;
using Aitex.Core.UI.MVVM;
using MECF.Framework.Simulator.Core.Driver;
namespace MECF.Framework.Simulator.Core.Commons
{
public class SerialPortDeviceViewModel : TimerViewModelBase
{
public List<string> PortList { get; set; }
public ICommand ClearLogCommand { get; set; }
public ICommand EnableCommand { get; set; }
public ICommand DisableCommand { get; set; }
public bool IsEnableEnable => !_simulator.IsEnabled;
public bool IsEnableDisable => _simulator.IsEnabled;
public string RemoteConnection => _simulator.RemoteConnection;
public string LocalPort => _simulator.PortName;
public bool IsConnected => _simulator.IsConnected;
public string ConnectionStatus
{
get
{
if (_simulator.IsEnabled)
return "Receiving";
return "Disable";
}
}
public string LocalPortSetPoint { get; set; }
public ObservableCollection<TransactionLogItem> TransactionLogItems { get; set; }
protected SerialPortDeviceSimulator _simulator;
public SerialPortDeviceViewModel(string name) : base(name)
{
ClearLogCommand = new DelegateCommand<string>(ClearLog);
EnableCommand = new DelegateCommand<string>(Enable);
DisableCommand = new DelegateCommand<string>(Disable);
TransactionLogItems = new ObservableCollection<TransactionLogItem>();
PortList = new List<string>(SerialPort.GetPortNames());
}
protected void Init(SerialPortDeviceSimulator sim, bool enable = true)
{
LocalPortSetPoint = sim.PortName;
InvokePropertyChanged("LocalPortSetPoint");
_simulator = sim;
_simulator.MessageOut += _simulator_MessageOut;
_simulator.MessageIn += _simulator_MessageIn;
if (enable)
_simulator.Enable();
}
private void Disable(string obj)
{
_simulator.Disable();
}
private void Enable(string obj)
{
_simulator.PortName = LocalPortSetPoint;
_simulator.Enable();
}
private void ClearLog(string obj)
{
TransactionLogItems.Clear();
}
private void _simulator_MessageIn(string obj)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TransactionLogItems.Add(new TransactionLogItem() { Incoming = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });
while (TransactionLogItems.Count > 100)
{
TransactionLogItems.RemoveAt(0);
}
}));
}
private void _simulator_MessageOut(string obj)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TransactionLogItems.Add(new TransactionLogItem() { Outgoing = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });
while (TransactionLogItems.Count > 100)
{
TransactionLogItems.RemoveAt(0);
}
}));
}
protected override void Poll()
{
if(Application.Current != null)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
InvokePropertyChanged();
}));
}
}
}
}
@@ -0,0 +1,65 @@
<UserControl
x:Class="MECF.Framework.Simulator.Core.Commons.SerialPortTitleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MECF.Framework.Simulator.Core.Commons"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="100"
d:DesignWidth="800"
Background="LightBlue"
mc:Ignorable="d">
<UserControl.Resources>
<local:ConnectionStatusBackgroundConverter x:Key="connectionStatusBackgroundConverter" />
<Style TargetType="Label">
<Setter Property="FontSize" Value="16" />
<Setter Property="Padding" Value="10,0,10,0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Label
Grid.Row="0"
Height="50"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Background="{Binding IsConnected, Converter={StaticResource connectionStatusBackgroundConverter}}"
Content="{Binding Title}"
FontSize="20" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<ComboBox
Width="120"
Height="35"
Margin="20,0,0,0"
VerticalContentAlignment="Center"
ItemsSource="{Binding PortList}"
SelectedItem="{Binding LocalPortSetPoint, Mode=TwoWay}" />
<Label Content="Port:" />
<Label Content="{Binding LocalPort}" />
<Label Content="{Binding ConnectionStatus}" />
<Button
Width="100"
Height="35"
Command="{Binding EnableCommand}"
Content="Enable"
IsEnabled="{Binding IsEnableEnable}" />
<Button
Width="100"
Height="35"
Command="{Binding DisableCommand}"
Content="Disable"
IsEnabled="{Binding IsEnableDisable}" />
</StackPanel>
</Grid>
</UserControl>
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MECF.Framework.Simulator.Core.Commons
{
/// <summary>
/// SerialPortTitleView.xaml 的交互逻辑
/// </summary>
public partial class SerialPortTitleView : UserControl
{
public SerialPortTitleView()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,77 @@
using MECF.Framework.Common.Communications;
using MECF.Framework.Simulator.Core.Driver;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MECF.Framework.Simulator.Core.Commons
{
public class SimpleSocketDeviceSimulator : DeviceSimulator
{
public override bool IsEnabled
{
get { return _socket != null && _socket.IsConnected; }
}
public override bool IsConnected
{
get { return IsEnabled; }
}
public string PortName
{
get { return _port.ToString(); }
set { _port = int.Parse(value); }
}
public int LocalPort
{
get { return _port; }
set
{
{
_port = value;
}
}
}
private AsynSocketServer _socket;
int _port;
public SimpleSocketDeviceSimulator(int port, int commandIndex, string lineDelimiter, char msgDelimiter, bool isAscii = true)
: base(commandIndex, lineDelimiter, msgDelimiter)
{
_port = port;
_socket = new AsynSocketServer("127.0.0.1" , port, isAscii, lineDelimiter);
_socket.OnDataChanged += OnReadMessage;
_socket.OnBinaryDataChanged += OnReadMessage;
_socket.OnErrorHappened += OnErrorMessage;
}
public void Enable()
{
_socket.Start();
}
public void Disable()
{
_socket.Dispose();
}
protected override void ProcessWriteMessage(string msg)
{
_socket.Write(msg);
}
protected override void ProcessWriteMessage(byte[] msg)
{
_socket.Write(msg);
}
}
}
@@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Aitex.Core.Account;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications.Tcp.Socket.Framing;
using MECF.Framework.Common.Communications.Tcp.Socket.Server.APM;
using MECF.Framework.Common.Communications.Tcp.Socket.Server.APM.EventArgs;
namespace MECF.Framework.Simulator.Core.Driver
{
public class SocketDeviceSimulator : DeviceSimulator, IDisposable
{
public override bool IsEnabled
{
get { return _server != null && _server.IsListening; }
}
public override bool IsConnected
{
get { return IsEnabled && _session != null; }
}
public int LocalPort
{
get { return _port; }
set {
{
IPEndPoint ip = _server.ListenedEndPoint;
ip.Port = value;
_server.ListenedEndPoint = ip;
} }
}
public string RemoteConnection
{
get
{
if (!IsConnected)
return "--";
TcpSocketSession session = _session;
return string.Format("{0}:{1}", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port);
}
}
private TcpSocketServer _server;
private TcpSocketSession _session;
private PeriodicJob _thread;
private int _port = 0;
private bool _enable;
public SocketDeviceSimulator(int port, int commandIndex, string lineDelimiter, char msgDelimiter, int cmdMaxLength = 4)
: base(commandIndex, lineDelimiter, msgDelimiter, cmdMaxLength)
{
_port = port;
TcpSocketServerConfiguration config = new TcpSocketServerConfiguration()
{
FrameBuilder = new LineBasedFrameBuilder(new LineDelimiter(lineDelimiter)),
};
_server = new TcpSocketServer(IPAddress.Parse("127.0.0.1"), port, config);
_server.ClientConnected += new EventHandler<TcpClientConnectedEventArgs>(ClientConnected);
_server.ClientDisconnected += new EventHandler<TcpClientDisconnectedEventArgs>(ClientDisconnected);
_server.ClientDataReceived += new EventHandler<TcpClientDataReceivedEventArgs>(ClientDataReceived);
_thread = new PeriodicJob(100, OnMonitor, "SocketSeverLisener", true);
}
private bool OnMonitor()
{
if (_enable)
{
if (!_server.IsListening)
{
_server.Listen();
}
}
else
{
if (_server.IsListening)
{
_server.Shutdown();
}
}
return true;
}
public void Enable()
{
_enable = true;
}
public void Disable()
{
_enable = false;
}
void ClientDataReceived(object sender, TcpClientDataReceivedEventArgs e)
{
if (ProcessReceivedData(e))
return;
OnReadMessage(Encoding.UTF8.GetString(e.Data, e.DataOffset, e.DataLength));
}
public virtual bool ProcessReceivedData(TcpClientDataReceivedEventArgs e)
{
return false;
}
void ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
{
_server.CloseSession(_session.SessionKey);
_session = null;
}
void ClientConnected(object sender, TcpClientConnectedEventArgs e)
{
_session = e.Session;
}
protected override void ProcessWriteMessage(string msg)
{
if (IsEnabled && _session != null)
{
_session.Send(Encoding.ASCII.GetBytes(msg));
}
}
public void Dispose()
{
Disable();
}
}
}
@@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Aitex.Core.UI.MVVM;
using MECF.Framework.Simulator.Core.Driver;
namespace MECF.Framework.Simulator.Core.Commons
{
public class SocketDeviceViewModel:TimerViewModelBase
{
public ICommand ClearLogCommand { get; set; }
public ICommand EnableCommand { get; set; }
public ICommand DisableCommand { get; set; }
public bool IsEnableEnable
{
get { return !_simulator.IsEnabled; }
}
public bool IsEnableDisable
{
get { return _simulator.IsEnabled; }
}
public bool IsConnected
{
get { return _simulator.IsConnected; }
}
public int LocalPort
{
get { return _simulator.LocalPort; }
}
public string RemoteConnection
{
get { return _simulator.RemoteConnection; }
}
public string ConnectionStatus
{
get
{
if (_simulator.IsConnected)
return "Connected";
if (_simulator.IsEnabled)
return "Listening";
return "Disable";
}
}
public string LocalPortSetPoint { get; set; }
public ObservableCollection<TransactionLogItem> TransactionLogItems { get; set; }
protected SocketDeviceSimulator _simulator;
public SocketDeviceViewModel(string name) : base(name)
{
ClearLogCommand = new DelegateCommand<string>(ClearLog);
EnableCommand = new DelegateCommand<string>(Enable);
DisableCommand = new DelegateCommand<string>(Disable);
TransactionLogItems = new ObservableCollection<TransactionLogItem>();
LocalPortSetPoint = "";
}
protected void Init(SocketDeviceSimulator sim, bool enable=true)
{
LocalPortSetPoint = sim.LocalPort.ToString();
_simulator = sim;
_simulator.MessageOut += _simulator_MessageOut;
_simulator.MessageIn += _simulator_MessageIn;
if (enable)
_simulator.Enable();
}
private void Disable(string obj)
{
_simulator.Disable();
}
private void Enable(string obj)
{
int port;
if (int.TryParse(LocalPortSetPoint, out port))
_simulator.LocalPort = port;
_simulator.Enable();
}
private void ClearLog(string obj)
{
TransactionLogItems.Clear();
}
private void _simulator_MessageIn(string obj)
{
if(!string.IsNullOrEmpty(obj))
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TransactionLogItems.Add(new TransactionLogItem() { Incoming = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });
}));
}
}
private void _simulator_MessageOut(string obj)
{
if (!string.IsNullOrEmpty(obj))
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TransactionLogItems.Add(new TransactionLogItem() { Outgoing = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });
}));
}
}
protected override void Poll()
{
if (Application.Current != null)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
InvokeAllPropertyChanged();
}));
}
}
}
public class SimpleSocketDeviceViewModel : TimerViewModelBase
{
public ICommand ClearLogCommand { get; set; }
public ICommand EnableCommand { get; set; }
public ICommand DisableCommand { get; set; }
public bool IsEnableEnable
{
get { return !_simulator.IsEnabled; }
}
public bool IsEnableDisable
{
get { return _simulator.IsEnabled; }
}
public bool IsConnected
{
get { return _simulator.IsConnected; }
}
public int LocalPort
{
get { return _simulator.LocalPort; }
}
//public string RemoteConnection
//{
// get { return _simulator.RemoteConnection; }
//}
public string ConnectionStatus
{
get
{
if (_simulator.IsConnected)
return "Connected";
if (_simulator.IsEnabled)
return "Listening";
return "Disable";
}
}
public string LocalPortSetPoint { get; set; }
public ObservableCollection<TransactionLogItem> TransactionLogItems { get; set; }
protected SimpleSocketDeviceSimulator _simulator;
public SimpleSocketDeviceViewModel(string name) : base(name)
{
ClearLogCommand = new DelegateCommand<string>(ClearLog);
EnableCommand = new DelegateCommand<string>(Enable);
DisableCommand = new DelegateCommand<string>(Disable);
TransactionLogItems = new ObservableCollection<TransactionLogItem>();
LocalPortSetPoint = "";
}
protected void Init(SimpleSocketDeviceSimulator sim, bool enable = true)
{
LocalPortSetPoint = sim.LocalPort.ToString();
_simulator = sim;
_simulator.MessageOut += _simulator_MessageOut;
_simulator.MessageIn += _simulator_MessageIn;
if (enable)
_simulator.Enable();
}
private void Disable(string obj)
{
_simulator.Disable();
}
private void Enable(string obj)
{
int port;
if (int.TryParse(LocalPortSetPoint, out port))
_simulator.LocalPort = port;
_simulator.Enable();
}
private void ClearLog(string obj)
{
TransactionLogItems.Clear();
}
private void _simulator_MessageIn(string obj)
{
if(!string.IsNullOrEmpty(obj))
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TransactionLogItems.Add(new TransactionLogItem() { Incoming = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });
}));
}
}
private void _simulator_MessageOut(string obj)
{
if (!string.IsNullOrEmpty(obj))
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TransactionLogItems.Add(new TransactionLogItem() { Outgoing = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });
}));
}
}
protected override void Poll()
{
if (Application.Current != null)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
InvokeAllPropertyChanged();
}));
}
}
}
}
@@ -0,0 +1,66 @@
<UserControl
x:Class="MECF.Framework.Simulator.Core.Commons.SocketTitleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MECF.Framework.Simulator.Core.Commons"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="100"
d:DesignWidth="800"
Background="LightBlue"
mc:Ignorable="d">
<UserControl.Resources>
<local:ConnectionStatusBackgroundConverter x:Key="connectionStatusBackgroundConverter" />
<Style TargetType="Label">
<Setter Property="FontSize" Value="16" />
<Setter Property="Padding" Value="10,0,10,0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Label
Grid.Row="0"
Height="50"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Background="{Binding IsConnected, Converter={StaticResource connectionStatusBackgroundConverter}}"
Content="{Binding Title}"
FontSize="20" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBox
Width="120"
Height="35"
Margin="20,0,0,0"
VerticalContentAlignment="Center"
Text="{Binding LocalPortSetPoint, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Label Content="Listen port:" />
<Label Content="{Binding LocalPortSetPoint}" />
<Label Content="{Binding ConnectionStatus}" />
<Button
Width="100"
Height="35"
Command="{Binding EnableCommand}"
Content="Enable"
IsEnabled="{Binding IsEnableEnable}" />
<Button
Width="100"
Height="35"
Command="{Binding DisableCommand}"
Content="Disable"
IsEnabled="{Binding IsEnableDisable}" />
<Label Content="Connection:" />
<Label Content="{Binding RemoteConnection}" />
</StackPanel>
</Grid>
</UserControl>
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MECF.Framework.Simulator.Core.Commons
{
/// <summary>
/// SocketTitleView.xaml 的交互逻辑
/// </summary>
public partial class SocketTitleView : UserControl
{
public SocketTitleView()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MECF.Framework.Simulator.Core.Driver
{
public class TransactionLogItem
{
public string OccurTime { get; set; }
public string Outgoing { get; set; }
public string Incoming { get; set; }
}
}
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using Aitex.Core.UI.ControlDataContext;
namespace MECF.Framework.Simulator.Core.Commons
{
public class ConnectionStatusBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isConnected = value != null && (bool) value;
return isConnected ? "Green" : "Yellow";
}
public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}