LIN 调度表功能同步 25002

This commit is contained in:
2026-01-05 22:07:54 +08:00
parent cae76745e5
commit 427cdc5305
17 changed files with 2225 additions and 73 deletions

View File

@@ -31,5 +31,12 @@ namespace CapMachine.Model.CANLIN
/// </summary>
[Column(Name = "LdfPath", IsNullable = false, StringLength = 500)]
public string? LdfPath { get; set; }
/// <summary>
/// 调度表是否启用
/// </summary>
[Column(Name = "SchEnable")]
public bool SchEnable { get; set; }
}
}

View File

@@ -4,7 +4,7 @@ namespace CapMachine.Model.CANLIN
{
/// <summary>
/// 调度表的配置
/// 其实这些调度表是在DBC中有的,但是图莫斯的驱动没有读取到这些信息
/// 其实这些调度表是在LDF中有的,但是图莫斯的驱动没有读取到这些信息
/// 那么我们在系统层面进行操作和保存这些信息
/// </summary>
[Table(Name = "LINScheduleConfig")]
@@ -17,11 +17,29 @@ namespace CapMachine.Model.CANLIN
public long Id { get; set; }
/// <summary>
/// 消息名称
/// 是否启用
/// </summary>
[Column(Name = "IsActive")]
public bool IsActive { get; set; }
/// <summary>
/// 帧/报文是否被选中(属于当前调度表内生效的帧)
/// </summary>
[Column(Name = "IsMsgActived")]
public bool IsMsgActived { get; set; }
/// <summary>
/// 消息名称/帧名称
/// </summary>
[Column(Name = "MsgName")]
public string? MsgName { get; set; }
/// <summary>
/// 消息名称/帧名称的Index
/// </summary>
[Column(Name = "MsgNameIndex")]
public int MsgNameIndex { get; set; }
/// <summary>
/// 消息的周期
/// </summary>
@@ -40,7 +58,7 @@ namespace CapMachine.Model.CANLIN
/// LDF中可能有多个调度器名称
/// </summary>
[Column(Name = "SchTabName")]
public int SchTabName { get; set; }
public string? SchTabName { get; set; }
/// <summary>

View File

@@ -200,6 +200,9 @@ namespace CapMachine.Wpf
containerRegistry.RegisterDialog<DialogSuperHeatCoolConfigView, DialogSuperHeatCoolConfigViewModel>();
containerRegistry.RegisterDialog<DialogLogicRuleView, DialogLogicRuleViewModel>();
containerRegistry.RegisterDialog<DialogCANSchConfigView, DialogCANSchConfigViewModel>();
containerRegistry.RegisterDialog<DialogLINSchConfigView, DialogLINSchConfigViewModel>();
containerRegistry.RegisterDialog<SplashScreenView, SplashScreenViewModel>();

View File

@@ -43,5 +43,16 @@ namespace CapMachine.Wpf.Dtos
get { return _LdfPath; }
set { _LdfPath = value; RaisePropertyChanged(); }
}
private bool _SchEnable;
/// <summary>
/// 调度表是否启用
/// </summary>
public bool SchEnable
{
get { return _SchEnable; }
set { _SchEnable = value; RaisePropertyChanged(); }
}
}
}

View File

@@ -0,0 +1,105 @@
using CapMachine.Model.CANLIN;
using Prism.Mvvm;
namespace CapMachine.Wpf.Dtos
{
public class LINScheduleConfigDto : BindableBase
{
/// <summary>
/// 主键
/// </summary>
public long Id { get; set; }
private bool _IsActive;
/// <summary>
/// 是否激活
/// </summary>
public bool IsActive
{
get { return _IsActive; }
set { _IsActive = value; RaisePropertyChanged(); }
}
private bool _IsMsgActived;
/// <summary>
/// 帧/报文是否被选中(隶属某个调度表)
/// </summary>
public bool IsMsgActived
{
get { return _IsMsgActived; }
set { _IsMsgActived = value; RaisePropertyChanged(); }
}
private string? _MsgName;
/// <summary>
/// 消息名称/帧名称
/// </summary>
public string? MsgName
{
get { return _MsgName; }
set { _MsgName = value; RaisePropertyChanged(); }
}
private int _MsgNameIndex;
/// <summary>
/// 消息名称/帧名称的Index
/// </summary>
public int MsgNameIndex
{
get { return _MsgNameIndex; }
set { _MsgNameIndex = value; RaisePropertyChanged(); }
}
private int _Cycle;
/// <summary>
/// 周期
/// </summary>
public int Cycle
{
get { return _Cycle; }
set { _Cycle = value; RaisePropertyChanged(); }
}
private int _SchTabIndex;
/// <summary>
/// 调度表的Index序列
/// </summary>
public int SchTabIndex
{
get { return _SchTabIndex; }
set { _SchTabIndex = value; RaisePropertyChanged(); }
}
private string? _SchTabName;
/// <summary>
/// 调度表的名称
/// </summary>
public string? SchTabName
{
get { return _SchTabName; }
set { _SchTabName = value; RaisePropertyChanged(); }
}
///// <summary>
///// 在更新调度表数据时,我们有一个整体的帧数据指令集合,但是这些帧数据集合,分属于不同的调度表,
///// 这个在开始时生成整体的帧数据指令集合才会把这个MsgIndex分配上这个不需要保存到数据库中对接使用
///// </summary>
//public int MsgIndex { get; set; }
/// <summary>
/// 程序的ID
/// </summary>
public long CanLinConfigProId { get; set; }
private CanLinConfigPro _CanLinConfigPro;
/// <summary>
/// 所属的程序
/// </summary>
public CanLinConfigPro CanLinConfigPro
{
get { return _CanLinConfigPro; }
set { _CanLinConfigPro = value; RaisePropertyChanged(); }
}
}
}

View File

@@ -69,5 +69,16 @@ namespace CapMachine.Wpf.LinDrive
public static extern Int32 LDF_ExeFrameToBus(UInt64 LDFHandle, StringBuilder pFrameName, byte FillBitValue);
[DllImport("USB2XXX.dll")]
public static extern Int32 LDF_ExeSchToBus(UInt64 LDFHandle, StringBuilder pSchName, byte FillBitValue);
[DllImport("USB2XXX.dll")]
public static extern Int32 LDF_SetSchToTable(UInt64 LDFHandle, StringBuilder pSchName, byte FillBitValue);
[DllImport("USB2XXX.dll")]
public static extern Int32 LDF_GetRawMsg(UInt64 LDFHandle, IntPtr pLINMsg, int BufferSize);
[DllImport("USB2XXX.dll")]
public static extern Int32 LDF_SyncMsgToValue(UInt64 LDFHandle, USB2LIN_EX.LIN_EX_MSG[] pLINMsg, int MsgLen);
[DllImport("USB2XXX.dll")]
public static extern Int32 LDF_StopSchTable(UInt64 LDFHandle);
[DllImport("USB2XXX.dll")]
public static extern Int32 LDF_Release(UInt64 LDFHandle);
}
}

View File

@@ -1,4 +1,5 @@
using System;
using CapMachine.Wpf.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -26,10 +27,40 @@ namespace CapMachine.Wpf.LinDrive
/// </summary>
public string? SignalName { get; set; }
/// <summary>
/// 指令数据改变Handler
/// 改变发送消息名称/帧名称
/// </summary>
public event EventHandler<string>? LinCmdDataChangedHandler;
private double _SignalCmdValue;
/// <summary>
/// 指令值
/// 没有的话,则给默认值
/// </summary>
public double SignalCmdValue { get; set; }
public double SignalCmdValue
{
get { return _SignalCmdValue; }
set
{
if (_SignalCmdValue != value)
{
_SignalCmdValue = value;
LinCmdDataChangedHandler?.Invoke(this, MsgName!);
}
}
}
///// <summary>
///// 逻辑规则Id
///// </summary>
//public long LogicRuleId { get; set; }
/// <summary>
/// CanLinConfig的逻辑转换规则
/// 比如速度下发的数据SV是4000但是下发到CAN的值是40可能是其他的逻辑转换规则这里就是保存其中的逻辑规则
/// </summary>
public LogicRuleDto? LogicRuleDto { get; set; }
}
}

View File

@@ -62,7 +62,7 @@ namespace CapMachine.Wpf.LinDrive
}
}
private StringBuilder _SignalRtValueSb = new StringBuilder(10);
private StringBuilder _SignalRtValueSb = new StringBuilder(16);
/// <summary>
/// 信号实时值 StringBuilder
/// </summary>
@@ -71,12 +71,24 @@ namespace CapMachine.Wpf.LinDrive
get { return _SignalRtValueSb; }
set
{
//if (_SignalRtValueSb != value)
//{
SignalRtValue = value.ToString();
_SignalRtValueSb = value;
//}
if (value == null)
{
if (_SignalRtValue != string.Empty)
{
_SignalRtValueSb.Clear();
SignalRtValue = string.Empty;
}
return;
}
// 复制内容到内部可变缓冲区,避免多个模型共享同一个 StringBuilder 实例
var str = value.ToString();
if (!string.Equals(_SignalRtValue, str, StringComparison.Ordinal))
{
_SignalRtValueSb.Clear();
_SignalRtValueSb.Append(str);
SignalRtValue = str;
}
}
}

View File

@@ -1,4 +1,6 @@
using CapMachine.Wpf.CanDrive;
using CapMachine.Model.CANLIN;
using CapMachine.Wpf.CanDrive;
using CapMachine.Wpf.Dtos;
using CapMachine.Wpf.Services;
using ImTools;
using Microsoft.VisualBasic;
@@ -26,16 +28,19 @@ namespace CapMachine.Wpf.LinDrive
/// 设备Handles集合
/// </summary>
public Int32[] DevHandles { get; set; } = new Int32[20];
/// <summary>
/// 设备Handles
/// 设备句柄本质为设备序号的低4字节可以通过调用USB_ScanDevice函数获得
/// </summary>
public Int32 DevHandle { get; set; } = 0;
/// <summary>
/// Lin的Index
/// LIN通道索引号填0或者1若只有一个通道LIN则填0.
/// </summary>
public Byte LINIndex { get; set; } = 0;
/// <summary>
/// Lin的连接State
/// </summary>
@@ -55,22 +60,59 @@ namespace CapMachine.Wpf.LinDrive
{
ContainerProvider = containerProvider;
HighSpeedDataService = ContainerProvider.Resolve<HighSpeedDataService>();
LoggerService = ContainerProvider.Resolve<ILogService>();
//Stopwatch.Frequency表示高精度计时器每秒的计数次数ticks/秒每毫秒的ticks数 = 每秒的ticks数 ÷ 1000
TicksPerMs = Stopwatch.Frequency / 1000.0;
}
/// <summary>
/// Logger 实例
/// </summary>
public ILogService LoggerService { get; set; }
/// <summary>
/// HighSpeedDataService 实例
/// </summary>
public HighSpeedDataService HighSpeedDataService { get; set; }
/// <summary>
/// 接收优化上下文:缓存帧与信号的 StringBuilder避免循环中重复分配
/// </summary>
private class SignalReadCtx
{
public string SignalName { get; set; }
public StringBuilder SignalNameSB { get; set; }
public LinLdfModel ModelRef { get; set; }
}
private class FrameReadCtx
{
public string MsgName { get; set; }
public StringBuilder MsgNameSB { get; set; }
public bool IsMasterFrame { get; set; }
public List<SignalReadCtx> Signals { get; set; } = new List<SignalReadCtx>();
}
private List<FrameReadCtx> RecvFrameCtxs = new List<FrameReadCtx>();
// 接收缓冲池(重用,避免每轮分配)
private IntPtr RecvMsgBufferPtr = IntPtr.Zero;
private int RecvMsgBufferCapacity = 1024;
private readonly int LinMsgSize = Marshal.SizeOf(typeof(USB2LIN_EX.LIN_EX_MSG));
// 控制台调试输出开关(默认关闭,防止日志风暴)
public bool EnableConsoleDebugLog { get; set; } = false;
// 保护接收缓冲的并发锁(接收读与关闭释放之间的互斥)
private readonly object RecvBufferSync = new object();
/// <summary>
/// 开始LDF文件写入
/// </summary>
public ObservableCollection<LinLdfModel> StartLdf(string LdfPath)
{
LDF_Parser(LdfPath);
BuildRecvFrameCtxs();
return ListLinLdfModel;
}
@@ -152,6 +194,17 @@ namespace CapMachine.Wpf.LinDrive
/// </summary>
public UInt64 LDFHandle { get; set; }
/// <summary>
/// LIN波特率从LDF读取
/// </summary>
public int LINBaudRate { get; private set; }
/// <summary>
/// 当前正在适配器中运行的调度表名称(用于增量刷新)
/// 同一个时刻只能运行一个调度表
/// </summary>
public string ActiveSchName { get; private set; }
/// <summary>
/// LDF消息集合
/// 包括读取的实时值和数据
@@ -163,6 +216,36 @@ namespace CapMachine.Wpf.LinDrive
/// </summary>
public List<LinCmdData> CmdData { get; set; } = new List<LinCmdData>();
/// <summary>
/// 加载要发送的数据(订阅数据变化事件)
/// 一般是激活后才注册事件
/// </summary>
/// <param name="cmdData"></param>
public void LoadCmdDataToDrive(List<LinCmdData> cmdData)
{
// 取消订阅旧数据源事件
if (CmdData != null && CmdData.Count > 0)
{
foreach (var cmd in CmdData)
{
cmd.LinCmdDataChangedHandler -= CmdData_LinCmdDataChangedHandler;
}
}
// 设置新数据源并订阅事件
CmdData = cmdData ?? new List<LinCmdData>();
foreach (var cmd in CmdData)
{
cmd.LinCmdDataChangedHandler += CmdData_LinCmdDataChangedHandler;
}
}
/// <summary>
/// 当前激活调度表下,启用的帧/报文名称集合(来自 ListLINScheduleConfig 的 IsMsgActived
/// 为空(null) 表示不过滤,使用所有 CmdData 中的帧;非空则仅对包含在集合内的帧做信号更新与下发。
/// </summary>
private HashSet<string>? ActiveMsgNames;
/// <summary>
/// ******************【1】*********************
/// 是否存在Dll文件
@@ -240,7 +323,23 @@ namespace CapMachine.Wpf.LinDrive
//读取LDF文件信息
Console.WriteLine("ProtocolVersion = {0}", LDFParser.LDF_GetProtocolVersion(LDFHandle));
Console.WriteLine("LINSpeed = {0}", LDFParser.LDF_GetLINSpeed(LDFHandle));
LINBaudRate = LDFParser.LDF_GetLINSpeed(LDFHandle);
Console.WriteLine("LINSpeed = {0}", LINBaudRate);
// 使用LDF中的波特率初始化LIN通道主机模式
var initRet = USB2LIN_EX.LIN_EX_Init(DevHandle, LINIndex, LINBaudRate, USB2LIN_EX.LIN_EX_MASTER);
if (initRet < USB2LIN_EX.LIN_EX_SUCCESS)
{
Console.WriteLine("LIN通道初始化失败!");
LdfParserState = false;
return;
}
else
{
Console.WriteLine("LIN通道初始化成功");
// 可选:开启适配器供电以驱动从节点(若硬件支持)
try { USB2LIN_EX.LIN_EX_CtrlPowerOut(DevHandle, LINIndex, 1); } catch { }
}
//读取主机名称
StringBuilder MasterName = new StringBuilder(64);
@@ -292,10 +391,49 @@ namespace CapMachine.Wpf.LinDrive
}
}
// 构建接收优化上下文,避免每次循环 GroupBy 与临时对象分配
BuildRecvFrameCtxs();
//解析成功
LdfParserState = true;
}
/// <summary>
/// 构建接收优化上下文
/// </summary>
private void BuildRecvFrameCtxs()
{
if (ListLinLdfModel == null || ListLinLdfModel.Count == 0)
{
RecvFrameCtxs = new List<FrameReadCtx>();
return;
}
var grouped = ListLinLdfModel.GroupBy(x => x.MsgName);
var list = new List<FrameReadCtx>();
foreach (var g in grouped)
{
var first = g.First();
var frame = new FrameReadCtx
{
MsgName = g.Key,
MsgNameSB = new StringBuilder(g.Key),
IsMasterFrame = (first.IsMasterFrame != null && first.IsMasterFrame.Contains("是"))
};
foreach (var model in g)
{
frame.Signals.Add(new SignalReadCtx
{
SignalName = model.SignalName,
SignalNameSB = new StringBuilder(model.SignalName),
ModelRef = model
});
}
list.Add(frame);
}
RecvFrameCtxs = list;
}
/// <summary>
/// 发送LIN数据
@@ -343,42 +481,79 @@ namespace CapMachine.Wpf.LinDrive
await Task.Delay(ReviceCycle);
try
{
var GroupMsg = ListLinLdfModel.GroupBy(x => x.MsgName);
foreach (var itemMsg in GroupMsg)
var frames = RecvFrameCtxs;
if (frames == null || frames.Count == 0)
{
var data = itemMsg.FirstOrDefault();
//非主机发送的指令帧就可以读取数据,因为函数 LDF_ExeFrameToBus【执行帧到总线若该帧的发布者是主机那么就是主机写数据否则就是主机读数据】
//那么主机发送和读取都是同一个函数。会导致跟Master主机也会在这里执行写入导致冲突出现错误。所以做一个排出
if (data != null && !data.IsMasterFrame!.Contains("是"))
IsReviceOk = true;
continue;
}
foreach (var frame in frames)
{
// 仅对从机发布的帧执行读取
if (frame.IsMasterFrame)
continue;
// 主机读操作,读取从机返回的数据值
LDFParser.LDF_ExeFrameToBus(LDFHandle, frame.MsgNameSB, 1);
foreach (var sig in frame.Signals)
{
//主机读操作,读取从机返回的数据值
LDFParser.LDF_ExeFrameToBus(LDFHandle, new StringBuilder(itemMsg.Key), 1);
foreach (var itemSignal in itemMsg)
LDFParser.LDF_GetSignalValueStr(LDFHandle, frame.MsgNameSB, sig.SignalNameSB, ReadValueStr);
sig.ModelRef.SignalRtValueSb = ReadValueStr;
}
}
// 从适配器读取原始LIN报文并写入高速记录服务
lock (RecvBufferSync)
{
if (RecvMsgBufferPtr == IntPtr.Zero)
{
RecvMsgBufferPtr = Marshal.AllocHGlobal(LinMsgSize * RecvMsgBufferCapacity);
if (EnableConsoleDebugLog) LoggerService?.Info("申请 LIN RecvMsgBufferPtr");
}
var msgPtRead = RecvMsgBufferPtr;
int linNum = LDFParser.LDF_GetRawMsg(LDFHandle, msgPtRead, RecvMsgBufferCapacity);
if (linNum > 0)
{
for (int i = 0; i < linNum; i++)
{
//LDFParser.LDF_ExeFrameToBus(LDFHandle, new StringBuilder(itemMsg.Key), 1);
LDFParser.LDF_GetSignalValueStr(LDFHandle, new StringBuilder(itemMsg.Key), new StringBuilder(itemSignal.SignalName), ReadValueStr);
itemSignal.SignalRtValueSb = ReadValueStr;
var msgPtr = (IntPtr)(msgPtRead + i * LinMsgSize);
var linMsg = (USB2LIN_EX.LIN_EX_MSG)Marshal.PtrToStructure(msgPtr, typeof(USB2LIN_EX.LIN_EX_MSG));
// 仅使用有效数据长度
int dataLen = linMsg.DataLen <= 0 ? 0 : Math.Min(linMsg.Data?.Length ?? 0, linMsg.DataLen);
string dataHex = dataLen > 0 ? BitConverter.ToString(linMsg.Data, 0, dataLen) : string.Empty;
if (EnableConsoleDebugLog)
{
Console.WriteLine($"LINMsg[{i}] PID=0x{linMsg.PID:X2} Type={linMsg.MsgType} CheckType={linMsg.CheckType} DataLen={linMsg.DataLen} Data={dataHex}");
}
// 推送到高速数据记录服务
HighSpeedDataService.AppendOrUpdateMsg(new Models.HighSpeed.CommMsg()
{
Category = "LIN",
MsgInfo = "0x" + linMsg.PID.ToString("X2"),
MsgData = dataHex,
Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
});
}
}
else if (linNum < 0 && EnableConsoleDebugLog)
{
Console.WriteLine("Get LIN raw data error!");
}
}
//StringBuilder ValueStr = new StringBuilder(64);
//LDFParser.LDF_ExeFrameToBus(LDFHandle, new StringBuilder("ID_DATA"), 1);
//LDFParser.LDF_GetSignalValueStr(LDFHandle, new StringBuilder("ID_DATA"), new StringBuilder("Supplier_ID"), ValueStr);
//Console.WriteLine("ID_DATA.Supplier_ID={0}", ValueStr);
//LDFParser.LDF_GetSignalValueStr(LDFHandle, new StringBuilder("ID_DATA"), new StringBuilder("Machine_ID"), ValueStr);
//Console.WriteLine("ID_DATA.Machine_ID={0}", ValueStr);
//LDFParser.LDF_GetSignalValueStr(LDFHandle, new StringBuilder("ID_DATA"), new StringBuilder("Chip_ID"), ValueStr);
//Console.WriteLine("ID_DATA.Chip_ID={0}", ValueStr);
IsReviceOk = true;
}
catch (Exception ex)
{
//LogService.Info($"时间:{DateTime.Now.ToString()}-【Meter】-{ex.Message}");
IsReviceOk = false;
LoggerService.Info($"{ex.Message}");
}
}
IsReviceOk = false;
});
}
@@ -454,6 +629,23 @@ namespace CapMachine.Wpf.LinDrive
}
private bool _IsReviceOk;
/// <summary>
/// 接收报文是否OK
/// </summary>
public bool IsReviceOk
{
get { return _IsReviceOk; }
set
{
if (_IsReviceOk != value)
{
RaisePropertyChanged();
_IsReviceOk = value;
}
}
}
#region
@@ -543,6 +735,8 @@ namespace CapMachine.Wpf.LinDrive
// 严重延迟,重新校准
NextExecutionTime = Stopwatcher.ElapsedTicks;
Console.WriteLine("定时发送延迟过大,重新校准时间");
LoggerService.Info("定时发送延迟过大,重新校准时间");
}
// 使用Stopwatch记录实际的执行间隔而不是DateTime
@@ -551,7 +745,6 @@ namespace CapMachine.Wpf.LinDrive
//Console.WriteLine($"--当前时间(毫秒): {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
// 执行发送CAN逻辑
{
@@ -578,33 +771,39 @@ namespace CapMachine.Wpf.LinDrive
}
}
IsSendOk = true;
}
}
catch (TaskCanceledException)
{
IsSendOk = false;
// 任务被取消,正常退出
break;
}
catch (Exception ex)
{
IsSendOk = false;
Console.WriteLine($"LIN周期发送异常: {ex.Message}");
// 短暂暂停避免异常情况下CPU占用过高
await Task.Delay(10, token);
}
}
IsSendOk = false;
}
catch (Exception ex)
{
IsSendOk = false;
// 确保在任何情况下(正常退出、异常、取消)都会停止计时器
Stopwatcher.Stop();
LoggerService.Info("接收出现异常");
// 清理其他可能的资源
Console.WriteLine("LIN周期发送任务已结束资源已清理");
}
finally
{
IsSendOk = false;
// 确保在任何情况下(正常退出、异常、取消)都会停止计时器
Stopwatcher.Stop();
}
@@ -625,6 +824,372 @@ namespace CapMachine.Wpf.LinDrive
#endregion
#region
/// <summary>
/// 指令数据变化时,更新调度表的线程锁
/// </summary>
private readonly object SchUpdateLock = new object();
private bool _SchEnable;
/// <summary>
/// 调度表使能
/// </summary>
public bool SchEnable
{
get { return _SchEnable; }
set
{
_SchEnable = value;
RaisePropertyChanged();
}
}
/// <summary>
/// 定时扫描更新数据 扫描Task
/// </summary>
private static Task CycleUpdateCmdTask { get; set; }
/// <summary>
/// 定时更新时间
/// 定时更新调度表的周期
/// </summary>
private int UpdateCycle { get; set; } = 5000;
/// <summary>
/// 调度表数量
/// </summary>
public int SchCount { get; set; }
/// <summary>
/// LIN 调度表的配置信息
/// </summary>
public List<LINScheduleConfigDto> ListLINScheduleConfig { get; set; }
/// <summary>
/// 获取LIN的LINScheduleConfig
/// </summary>
/// <returns></returns>
public List<LINScheduleConfig> GetLINScheduleConfigs()
{
List<LINScheduleConfig> LINScheduleConfigs = new List<LINScheduleConfig>();
SchCount = GetSchCount();
for (int i = 0; i < SchCount; i++)
{
var SchName = GetSchName(i);
var FrameCount = GetSchFrameCount(SchName);
for (int j = 0; j < FrameCount; j++)
{
LINScheduleConfigs.Add(new LINScheduleConfig()
{
SchTabName = GetSchName(i),
SchTabIndex = i,
MsgName = GetSchFrameName(SchName, j),
MsgNameIndex = j,
Cycle = 100,
IsActive = false,
});
}
}
return LINScheduleConfigs;
}
/// <summary>
/// 获取调度的帧的信号个数
/// 消息/报文的个数
/// 一个调度表包含多个帧/消息/报文
/// </summary>
/// <returns></returns>
public int GetSchFrameCount(string SchName)
{
return LDFParser.LDF_GetSchFrameQuantity(LDFHandle, new StringBuilder(SchName));
}
/// <summary>
/// 获取调度的帧的名称
/// </summary>
/// <returns></returns>
public string GetSchFrameName(string SchName, int FrameIndex)
{
StringBuilder FrameName = new StringBuilder();
LDFParser.LDF_GetSchFrameName(LDFHandle, new StringBuilder(SchName), FrameIndex, FrameName);
return FrameName.ToString();
}
/// <summary>
/// 获取调度表数量
/// </summary>
/// <returns></returns>
public int GetSchCount()
{
SchCount = LDFParser.LDF_GetSchQuantity(LDFHandle);
return SchCount;
}
/// <summary>
/// 获取调度表数量
/// </summary>
/// <returns></returns>
public string GetSchName(int index)
{
StringBuilder pSchName = new StringBuilder();
var SchResult = LDFParser.LDF_GetSchName(LDFHandle, index, pSchName);
return pSchName.ToString();
}
Random Random = new Random();
/// <summary>
/// 开始调度表执行
/// 同一个时刻只能运行一个调度表,如果有多个调度表,只能选择一个运行,
/// ********** 如果控制指令分布在不同的调度表中需要更改LDF文件的配置把控制的报文放在同一个调度表中 **********
/// </summary>
public void StartSchedule()
{
if (LDFHandle == 0)
return;
// 1) 将要执行的调度表烧入适配器并自动运行(若不指定,则启动全部调度表)
// 优先使用 ListLINScheduleConfig 指定的调度表名;否则默认取第一个
string selectedSch = string.Empty;
if (ListLINScheduleConfig != null && ListLINScheduleConfig.Count > 0)
{
selectedSch = ListLINScheduleConfig.FirstOrDefault(a => a.IsActive && !string.IsNullOrEmpty(a.SchTabName))?.SchTabName
?? ListLINScheduleConfig.FirstOrDefault(a => !string.IsNullOrEmpty(a.SchTabName))?.SchTabName;
}
if (string.IsNullOrEmpty(selectedSch))
{
// 回退为索引0的调度表
if (GetSchCount() > 0)
{
selectedSch = GetSchName(0);
LoggerService?.Info($"未指定调度表,默认启动调度表[{selectedSch}],注意当前调度表可能需要的调度表");
}
}
//当前激活的调度表
ActiveSchName = selectedSch;
// 计算当前激活调度表下的“被选中帧”集合IsMsgActived=true
if (!string.IsNullOrEmpty(ActiveSchName) && ListLINScheduleConfig != null)
{
var actives = ListLINScheduleConfig
.Where(d => d.IsActive && d.IsMsgActived && string.Equals(d.SchTabName ?? string.Empty, ActiveSchName ?? string.Empty, StringComparison.Ordinal))
.Select(d => d.MsgName)
.Where(n => !string.IsNullOrEmpty(n))
.Distinct()
.ToList();
ActiveMsgNames = actives.Count > 0 ? new HashSet<string>(actives) : new HashSet<string>();
}
else
{
ActiveMsgNames = null; // 不过滤
}
// 2) 先将当前指令值写入对应帧(可选,用于初始化,仅对被选中的帧)
if (CmdData != null && CmdData.Count > 0)
{
var groupMsg = CmdData.GroupBy(x => x.MsgName);
foreach (var itemMsg in groupMsg)
{
// 若设置了激活的帧集合,则进行过滤
if (ActiveMsgNames != null && !ActiveMsgNames.Contains(itemMsg.Key))
continue;
foreach (var itemSignal in itemMsg)
{
LDFParser.LDF_SetSignalValue(LDFHandle, new StringBuilder(itemMsg.Key), new StringBuilder(itemSignal.SignalName), itemSignal.SignalCmdValue);
}
}
}
// 3) 下发选中调度表到表格并自动执行
var ret = LDFParser.LDF_SetSchToTable(LDFHandle, new StringBuilder(ActiveSchName), 0);
if (ret < 0)
{
LoggerService?.Info($"启动调度表[{ActiveSchName}]失败, 返回:{ret}");
}
else
{
Console.WriteLine($"调度表[{ActiveSchName}]已启动(自动执行)");
LoggerService?.Info($"调度表[{ActiveSchName}]已启动(自动执行)");
}
// 4) 置位调度更新开关(事件驱动刷新,不再自动启动周期刷新任务)
//SchEnable = true;
// 不再自动启动周期更新任务,改为数据变化事件驱动刷新
// if (CycleUpdateCmdTask == null || CycleUpdateCmdTask.IsCompleted) { StartCycleUpdateCmd(); }
}
/// <summary>
/// 循环更新调度表的指令数据
/// 定时更新数据到调度表中
/// 被数值更新事件驱动的方法取代了
/// </summary>
public void StartCycleUpdateCmd()
{
CycleUpdateCmdTask = Task.Run(async () =>
{
while (IsCycleSend)
{
await Task.Delay(UpdateCycle);
try
{
if (CmdData.Count() == 0) return;
//防止有多个不同的消息名称/帧,每个帧单独处理发送
var GroupMsg = CmdData.GroupBy(x => x.MsgName);
foreach (var itemMsg in GroupMsg)
{
// 若设置了激活的帧集合,则进行过滤
if (ActiveMsgNames != null && !ActiveMsgNames.Contains(itemMsg.Key))
continue;
foreach (var itemSignal in itemMsg)
{
if (itemSignal.ConfigName.Contains("速"))
{
itemSignal.SignalCmdValue = 1250 + Random.NextDouble() * 1000;
}
//主机写操作,发送数据给从机
LDFParser.LDF_SetSignalValue(LDFHandle, new StringBuilder(itemMsg.Key), new StringBuilder(itemSignal.SignalName), itemSignal.SignalCmdValue);
}
////【0】参数注意
//LDFParser.LDF_ExeFrameToBus(LDFHandle, new StringBuilder(itemMsg.Key), 0);
//读取当前的指令帧数据LDF_ExeFrameToBus执行后就可以读取本身的数据
foreach (var item in ListLinLdfModel)
{
if (CmdData.Any(a => a.MsgName == item.MsgName)
&& (ActiveMsgNames == null || ActiveMsgNames.Contains(item.MsgName)))
{
LDFParser.LDF_GetSignalValueStr(LDFHandle, new StringBuilder(item.MsgName), new StringBuilder(item.SignalName), ReadValueStr);
item.SignalRtValueSb = ReadValueStr;
}
}
// 调度表已在适配器中自动执行,这里仅更新信号值即可
}
// 将更新后的信号值下发到适配器的自动调度表(刷新离线表的数据)
if (!string.IsNullOrEmpty(ActiveSchName))
{
var retPush = LDFParser.LDF_SetSchToTable(LDFHandle, new StringBuilder(ActiveSchName), 0);
if (retPush < 0)
{
LoggerService?.Info($"刷新调度表[{ActiveSchName}]失败, 返回:{retPush}");
}
}
IsSendOk = true;
}
catch (Exception ex)
{
IsSendOk = false;
LoggerService.Info($"时间:{DateTime.Now.ToString()}-【MSG】-{ex.Message}");
}
}
IsSendOk = false;
});
}
/// <summary>
/// 指令数据发生变化事件回调
/// </summary>
/// <param name="sender"></param>
/// <param name="e">消息/帧名称</param>
private void CmdData_LinCmdDataChangedHandler(object? sender, string e)
{
UpdateSchDataByCmdDataChanged(e);
}
/// <summary>
/// 指令数据变化时,按消息名增量刷新调度表数据
/// </summary>
/// <param name="changedMsgName">发生变化的帧名称</param>
private void UpdateSchDataByCmdDataChanged(string changedMsgName)
{
try
{
// 与CAN保持一致仅在循环发送开启且调度表使能时才更新
if (!IsCycleSend) return;
if (!SchEnable) return;
// 基础防御
if (LDFHandle == 0) return;
if (string.IsNullOrEmpty(ActiveSchName)) return;
if (string.IsNullOrEmpty(changedMsgName)) return;
// 若配置了激活帧过滤,则不在集合内的帧不更新
if (ActiveMsgNames != null && ActiveMsgNames.Count > 0 && !ActiveMsgNames.Contains(changedMsgName))
return;
lock (SchUpdateLock)
{
// 仅更新对应消息/帧的信号值
var relatedCmds = CmdData.Where(x => string.Equals(x.MsgName, changedMsgName, StringComparison.Ordinal));
foreach (var cmd in relatedCmds)
{
LDFParser.LDF_SetSignalValue(LDFHandle, new StringBuilder(changedMsgName), new StringBuilder(cmd.SignalName), cmd.SignalCmdValue);
}
//读取当前的指令帧数据,执行后就可以读取本身的数据
foreach (var item in ListLinLdfModel)
{
if (CmdData.Any(a => a.MsgName == item.MsgName))
{
LDFParser.LDF_GetSignalValueStr(LDFHandle, new StringBuilder(item.MsgName), new StringBuilder(item.SignalName), ReadValueStr);
item.SignalRtValueSb = ReadValueStr;
}
}
// 将更新后的信号值推送到适配器当前运行的调度表(离线表刷新)
var retPush = LDFParser.LDF_SetSchToTable(LDFHandle, new StringBuilder(ActiveSchName), 0);
if (retPush < 0)
{
IsSendOk = false;
LoggerService?.Info($"刷新调度表[{ActiveSchName}]失败, 返回:{retPush}");
}
else
{
IsSendOk = true;
//Console.WriteLine($"Update LIN Schedule Success -- Sch:[{ActiveSchName}] Msg:[{changedMsgName}]");
}
}
}
catch (Exception ex)
{
IsSendOk = false;
LoggerService?.Info($"时间:{DateTime.Now.ToString()}-【LIN_SCH】-{ex.Message}");
}
}
/// <summary>
/// 停止调度表自动执行
/// </summary>
public void StopSchedule()
{
try
{
IsCycleSend = false;
SchEnable = false;
ActiveMsgNames = null; // 清空激活帧过滤集合
if (LDFHandle != 0)
{
LDFParser.LDF_StopSchTable(LDFHandle);
}
}
catch (Exception ex)
{
LoggerService?.Info($"停止调度表异常: {ex.Message}");
}
}
#endregion
/// <summary>
/// 关闭设备
@@ -632,6 +1197,27 @@ namespace CapMachine.Wpf.LinDrive
public void CloseDevice()
{
//关闭设备
try
{
// 停止调度并释放LDF资源
if (LDFHandle != 0)
{
try { LDFParser.LDF_StopSchTable(LDFHandle); } catch { }
try { LDFParser.LDF_Release(LDFHandle); } catch { }
LDFHandle = 0;
}
// 释放接收缓冲区
lock (RecvBufferSync)
{
if (RecvMsgBufferPtr != IntPtr.Zero)
{
try { Marshal.FreeHGlobal(RecvMsgBufferPtr); }
catch { }
finally { RecvMsgBufferPtr = IntPtr.Zero; }
}
}
}
catch { }
USB_DEVICE.USB_CloseDevice(DevHandle);
OpenState = false;
LdfParserState = false;

View File

@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace CapMachine.Wpf.LinDrive
{
@@ -95,7 +90,12 @@ namespace CapMachine.Wpf.LinDrive
public static extern Int32 LIN_EX_MasterStopSch(Int32 DevHandle, Byte LINIndex);
[DllImport("USB2XXX.dll")]
public static extern Int32 LIN_EX_MasterGetSch(Int32 DevHandle, Byte LINIndex, IntPtr pLINMsg);
[DllImport("USB2XXX.dll")]
public static extern Int32 LIN_EX_MasterSetSchRunTimes(Int32 DevHandle, Byte LINIndex, UInt32 RunTimes);
[DllImport("USB2XXX.dll")]
public static extern Int64 LIN_EX_GetStartTime(Int32 DevHandle, Byte LINIndex);
[DllImport("USB2XXX.dll")]
public static extern Int32 LIN_EX_ResetStartTime(Int32 DevHandle, Byte LINIndex);
[DllImport("USB2XXX.dll")]
public static extern Int32 LIN_EX_MasterOfflineSch(Int32 DevHandle, Byte LINIndex, Int32 BaudRate, LIN_EX_MSG[] pLINMsg, Int32 MsgLen);
[DllImport("USB2XXX.dll")]

View File

@@ -1,15 +1,10 @@
using CapMachine.Model.CANLIN;
using CapMachine.Wpf.CanDrive;
using CapMachine.Wpf.Dtos;
using CapMachine.Wpf.LinDrive;
using ImTools;
using Prism.Ioc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CapMachine.Wpf.Services
{
@@ -20,15 +15,19 @@ namespace CapMachine.Wpf.Services
{
public HighSpeedDataService HighSpeedDataService { get; }
public LogicRuleService LogicRuleService { get; }
/// <summary>
/// 实例化函数
/// </summary>
public LinDriveService(HighSpeedDataService highSpeedDataService, IContainerProvider containerProvider)
public LinDriveService(HighSpeedDataService highSpeedDataService, IContainerProvider containerProvider, LogicRuleService logicRuleService)
{
ToomossLinDrive = new ToomossLin(containerProvider);
//高速数据服务
HighSpeedDataService = highSpeedDataService;
LogicRuleService = logicRuleService;
//ToomossLinDrive.StartLinDrive();
}
@@ -123,6 +122,11 @@ namespace CapMachine.Wpf.Services
/// </summary>
public List<LinCmdData> CmdData { get; set; } = new List<LinCmdData>();
/// <summary>
/// 调度表LIN配置信息
/// </summary>
public List<LINScheduleConfigDto> ListLINScheduleConfig { get; set; } = new List<LINScheduleConfigDto>();
/// <summary>
/// 增加发送的指令数据
/// </summary>
@@ -171,16 +175,32 @@ namespace CapMachine.Wpf.Services
/// <param name="canCmdData"></param>
public void UpdateSpeedCmdData(double SpeedData)
{
//if (SpeedLinCmdData != null)
//{
// SpeedLinCmdData.SignalCmdValue = SpeedData;
//}
if (SpeedLinCmdData != null)
{
SpeedLinCmdData.SignalCmdValue = SpeedData;
}
//if (EnableLinCmdData != null)
//{
// EnableLinCmdData.SignalCmdValue = 1;
//}
}
//首先是否判断是有斜率
if (SpeedLinCmdData.LogicRuleDto == null)
{
//没有启动逻辑规则处理
SpeedLinCmdData.SignalCmdValue = SpeedData;
}
else
{
//LogicRuleService.ApplyExpressionFast(SpeedData, SpeedCanCmdData.LogicRuleDto);
SpeedLinCmdData.SignalCmdValue = LogicRuleService.ApplyExpressionFast(SpeedData, SpeedLinCmdData.LogicRuleDto);
//Console.WriteLine($"实时转换后转速值:{SpeedCanCmdData.SignalCmdValue}-SV值:{SpeedData}");
}
//if (EnableLinCmdData != null)
//{
// EnableLinCmdData.SignalCmdValue = 1;
//}
}
}
/// <summary>
/// 更新压缩机使能数据
@@ -225,9 +245,25 @@ namespace CapMachine.Wpf.Services
/// <param name="IsEnable"></param>
public void UpdateCapPTCPwCmdData(double PTCPw)
{
//if (PTCPwCanCmdData != null)
//{
// PTCPwCanCmdData.SignalCmdValue = PTCPw;
//}
if (PTCPwCanCmdData != null)
{
PTCPwCanCmdData.SignalCmdValue = PTCPw;
//首先是否判断是有斜率
if (PTCPwCanCmdData.LogicRuleDto == null)
{
//没有启动逻辑规则处理
PTCPwCanCmdData.SignalCmdValue = PTCPw;
}
else
{
//LogicRuleService.ApplyExpressionFast(SpeedData, SpeedCanCmdData.LogicRuleDto);
PTCPwCanCmdData.SignalCmdValue = LogicRuleService.ApplyExpressionFast(PTCPw, PTCPwCanCmdData.LogicRuleDto);
//Console.WriteLine($"实时转换后转速值:{SpeedCanCmdData.SignalCmdValue}-SV值:{SpeedData}");
}
}
}
@@ -237,10 +273,27 @@ namespace CapMachine.Wpf.Services
/// <param name="IsEnable"></param>
public void UpdateCapPTCFlowCmdData(double Flow)
{
//if (PTCFlowCanCmdData != null)
//{
// PTCFlowCanCmdData.SignalCmdValue = Flow;
//}
if (PTCFlowCanCmdData != null)
{
PTCFlowCanCmdData.SignalCmdValue = Flow;
//首先是否判断是有斜率
if (PTCFlowCanCmdData.LogicRuleDto == null)
{
//没有启动逻辑规则处理
PTCFlowCanCmdData.SignalCmdValue = Flow;
}
else
{
//LogicRuleService.ApplyExpressionFast(SpeedData, SpeedCanCmdData.LogicRuleDto);
PTCFlowCanCmdData.SignalCmdValue = LogicRuleService.ApplyExpressionFast(Flow, PTCFlowCanCmdData.LogicRuleDto);
//Console.WriteLine($"实时转换后转速值:{SpeedCanCmdData.SignalCmdValue}-SV值:{SpeedData}");
}
}
}
/// <summary>
@@ -249,10 +302,27 @@ namespace CapMachine.Wpf.Services
/// <param name="IsEnable"></param>
public void UpdateCapPTCWaterTempCmdData(double WaterTemp)
{
//if (PTCWaterTempCanCmdData != null)
//{
// PTCWaterTempCanCmdData.SignalCmdValue = WaterTemp;
//}
if (PTCWaterTempCanCmdData != null)
{
PTCWaterTempCanCmdData.SignalCmdValue = WaterTemp;
//首先是否判断是有斜率
if (PTCWaterTempCanCmdData.LogicRuleDto == null)
{
//没有启动逻辑规则处理
PTCWaterTempCanCmdData.SignalCmdValue = WaterTemp;
}
else
{
//LogicRuleService.ApplyExpressionFast(SpeedData, SpeedCanCmdData.LogicRuleDto);
PTCWaterTempCanCmdData.SignalCmdValue = LogicRuleService.ApplyExpressionFast(WaterTemp, PTCWaterTempCanCmdData.LogicRuleDto);
//Console.WriteLine($"实时转换后转速值:{SpeedCanCmdData.SignalCmdValue}-SV值:{SpeedData}");
}
}
}
/// <summary>
@@ -288,14 +358,52 @@ namespace CapMachine.Wpf.Services
{
if (ToomossLinDrive.OpenState)
{
//来回取反设置
if (ToomossLinDrive.IsCycleSend == false)
{
if (CmdData.Count > 0)
{
ToomossLinDrive.IsCycleSend = true;
////订阅 CmdData 的数据变化事件,确保基于数据变化刷新调度表
//ToomossLinDrive.LoadCmdDataToDrive(CmdData);
ToomossLinDrive.CmdData = CmdData;
ToomossLinDrive.StartPrecisionCycleSendMsg();
//ToomossLinDrive.IsCycleSend = true;
//ToomossLinDrive.StartPrecisionCycleSendMsg();
//ToomossLinDrive.StartCycleSendMsg();
if (ToomossLinDrive.SchEnable)
{
//使用调度表的话,需要在调度表中配置信息后才可以进行操作
var GroupMsg = ToomossLinDrive.CmdData.GroupBy(a => a.MsgName).ToList();
foreach (var itemMsg in GroupMsg)
{
if (!ListLINScheduleConfig.ToList().Any(a => a.MsgName == itemMsg.Key))
{
System.Windows.MessageBox.Show($"你使能了调度表,但是调度表中没有设置【{itemMsg.Key}】信息,请设置后再操作", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Hand);
return;
}
}
if (ListLINScheduleConfig == null && ListLINScheduleConfig!.Count() == 0)
{
System.Windows.MessageBox.Show("调度表配置为空数据,请检查!将无法发送数据", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Hand);
return;
}
ToomossLinDrive.ListLINScheduleConfig = ListLINScheduleConfig!;
ToomossLinDrive.StartSchedule();
//ToomossLinDrive.StartCycleUpdateCmd();
}
else
{
//使用软件调度发送数据
ToomossLinDrive.StartPrecisionCycleSendMsg();
//ToomossCanDrive.StartCycleSendMsg();
}
ToomossLinDrive.IsCycleSend = true;
}
else
{
@@ -305,6 +413,11 @@ namespace CapMachine.Wpf.Services
else
{
ToomossLinDrive.IsCycleSend = false;
//如果是调度表的话,需要关闭调度表
if (ToomossLinDrive.SchEnable)
{
ToomossLinDrive.StopSchedule();
}
}
}

View File

@@ -0,0 +1,581 @@
using AutoMapper;
using CapMachine.Core;
using CapMachine.Model.CANLIN;
using CapMachine.Wpf.Dtos;
using CapMachine.Wpf.Services;
using Prism.Commands;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using System.Windows;
using System.Linq;
using System.ComponentModel;
using System;
namespace CapMachine.Wpf.ViewModels
{
public class DialogLINSchConfigViewModel : DialogViewModel
{
public DialogLINSchConfigViewModel(IFreeSql freeSql, IMapper mapper, LinDriveService linDriveService)
{
Title = "调度表 LIN 配置";
FreeSql = freeSql;
Mapper = mapper;
LinDriveService = linDriveService;
//默认只能用1号调度器
SchTabIndexCbxItems = new ObservableCollection<CbxItems>()
{
new CbxItems(){
Key="0",
Text="0",
},
//new CbxItems(){
// Key="1",
// Text="1",
//},
//new CbxItems(){
// Key="2",
// Text="2",
//},
//new CbxItems(){
// Key="3",
// Text="3",
//},
//new CbxItems(){
// Key="4",
// Text="4",
//},
};
// 初始化树结构集合
SchTabTree = new ObservableCollection<LinSchTabNode>();
}
public IFreeSql FreeSql { get; }
public IMapper Mapper { get; }
public LinDriveService LinDriveService { get; }
private string name;
/// <summary>
/// 名称
/// </summary>
public string Name
{
get { return name; }
set { name = value; RaisePropertyChanged(); }
}
private ObservableCollection<LINScheduleConfigDto> _ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>();
/// <summary>
/// LIN 调度表数据集合
/// </summary>
public ObservableCollection<LINScheduleConfigDto> ListLINScheduleConfigDto
{
get { return _ListLINScheduleConfigDto; }
set { _ListLINScheduleConfigDto = value; RaisePropertyChanged(); }
}
/// <summary>
/// 消息/帧报文信息集合
/// </summary>
public List<string> ListMsg { get; set; }
private ObservableCollection<CbxItems> _MsgCbxItems;
/// <summary>
/// 消息名称 集合信息
/// </summary>
public ObservableCollection<CbxItems> MsgCbxItems
{
get { return _MsgCbxItems; }
set { _MsgCbxItems = value; RaisePropertyChanged(); }
}
/// <summary>
/// 选中的程序的Id
/// </summary>
public long SelectCanLinConfigProId { get; set; }
private ObservableCollection<CbxItems> _SchTabIndexCbxItems;
/// <summary>
/// 调度器序号 集合信息
/// </summary>
public ObservableCollection<CbxItems> SchTabIndexCbxItems
{
get { return _SchTabIndexCbxItems; }
set { _SchTabIndexCbxItems = value; RaisePropertyChanged(); }
}
private LINScheduleConfigDto _CurSelectedItem;
/// <summary>
/// 选中的数据
/// </summary>
public LINScheduleConfigDto CurSelectedItem
{
get { return _CurSelectedItem; }
set { _CurSelectedItem = value; RaisePropertyChanged(); }
}
//================ TreeView 数据源与选择逻辑 ================
// 说明:
// 1) SchTabTree 为 XAML 中 TreeView 的 ItemsSource父节点为调度表 LinSchTabNode子节点为 LinMsgNode。
// 2) 仅允许“单选”一个调度表(父节点)。父节点上的 CheckBox 为 TwoWay 绑定 ViewModel 模型的 IsSelected 属性。
// 3) 我们在 BuildTree() 完成后,通过 AttachNodeHandlers() 给父节点订阅 PropertyChanged
// 当 IsSelected 变化时,统一走 OnSelectSchTab() 做单选互斥与子节点联动,避免在 XAML 上用行为触发器造成递归。
private ObservableCollection<LinSchTabNode> _SchTabTree;
/// <summary>
/// 调度表-消息 树结构数据源SchTabName消息/帧)
/// </summary>
public ObservableCollection<LinSchTabNode> SchTabTree
{
get { return _SchTabTree; }
set { _SchTabTree = value; RaisePropertyChanged(); }
}
// 防止选择联动时的递归重入。
// 在 OnSelectSchTab() 中统一设置 _isUpdatingSelection = true
// 以避免模型属性变化再次触发 Node_PropertyChanged() / OnSelectSchTab() 形成递归导致 StackOverflow。
private bool _isUpdatingSelection = false;
private DelegateCommand<LinSchTabNode> _SelectSchTabCmd;
/// <summary>
/// 选择/激活 调度表命令(单选),联动选中其下所有消息
/// </summary>
public DelegateCommand<LinSchTabNode> SelectSchTabCmd
{
get
{
if (_SelectSchTabCmd == null)
{
_SelectSchTabCmd = new DelegateCommand<LinSchTabNode>(OnSelectSchTab);
}
return _SelectSchTabCmd;
}
set { _SelectSchTabCmd = value; }
}
/// <summary>
/// 激活选中的调度表(父节点单选),并联动:
/// 1) 取消其它调度表的选中;
/// 2) 仅控制子节点可编辑状态(不强制选中/取消),子节点勾选独立由用户控制;
/// 3) 同步底层 ListLINScheduleConfigDto 的 IsActive只允许一个调度表 Active
/// 通过 _isUpdatingSelection 防重入,避免模型 -> 视图 -> 模型 的递归通知。
/// </summary>
/// <param name="node"></param>
private void OnSelectSchTab(LinSchTabNode node)
{
if (node == null) return;
if (_isUpdatingSelection) return;
try
{
_isUpdatingSelection = true;
// 单选:当前节点选中时,取消其它调度表选中
if (node.IsSelected)
{
foreach (var n in SchTabTree)
{
bool isTarget = ReferenceEquals(n, node);
n.IsSelected = isTarget;
// 仅控制可编辑性
foreach (var c in n.Children) c.CanEdit = isTarget;
}
}
else
{
// 取消选中:仅禁止子节点编辑,保留勾选状态
foreach (var c in node.Children) c.CanEdit = false;
}
// 同步 DTO 激活状态:按当前树中第一个被选中的调度表名写回
var active = SchTabTree?.FirstOrDefault(n => n.IsSelected);
foreach (var dto in ListLINScheduleConfigDto)
{
dto.IsActive = active != null && string.Equals(dto.SchTabName, active.SchTabName, StringComparison.Ordinal);
}
}
finally
{
_isUpdatingSelection = false;
}
}
/// <summary>
/// 基于当前 ListLINScheduleConfigDto 构建树结构。
/// - 将 DTO 以 SchTabName 分组,生成父节点;
/// - 子节点为每条消息/帧MsgName, MsgNameIndexIsSelected 与 DTO.IsActive 同步;
/// - 若出现多个分组均被标记 IsActive则仅保留第一个为选中其它重置为未选中保证单选约束
/// - 构建完成后调用 AttachNodeHandlers() 订阅父节点的 PropertyChanged实现勾选即联动。
/// </summary>
private void BuildTree()
{
var newTree = new ObservableCollection<LinSchTabNode>();
if (ListLINScheduleConfigDto != null && ListLINScheduleConfigDto.Any())
{
var groups = ListLINScheduleConfigDto
.GroupBy(x => x.SchTabName ?? string.Empty)
.OrderBy(g => g.Key);
foreach (var g in groups)
{
var node = new LinSchTabNode
{
SchTabName = g.Key,
IsSelected = g.Any(x => x.IsActive),
Children = new ObservableCollection<LinMsgNode>(
g.Select(x => new LinMsgNode
{
SchTabName = g.Key,
MsgName = x.MsgName ?? string.Empty,
MsgNameIndex = x.MsgNameIndex,
IsSelected = x.IsMsgActived,
CanEdit = g.Any(t => t.IsActive) // 仅激活的调度表可编辑
}))
};
newTree.Add(node);
}
// 如果没有任何 IsActive确保默认不选若存在多个组被标记保持第一个其他置为 false
var activeOnes = newTree.Where(n => n.IsSelected).ToList();
if (activeOnes.Count > 1)
{
var keep = activeOnes.First();
foreach (var n in activeOnes.Skip(1)) n.IsSelected = false;
foreach (var dto in ListLINScheduleConfigDto)
{
dto.IsActive = string.Equals(dto.SchTabName, keep.SchTabName, StringComparison.Ordinal);
}
}
}
SchTabTree = newTree;
// 绑定节点属性变化事件:
// - 父节点 IsSelected 变化 -> Node_PropertyChanged() -> OnSelectSchTab()
// - 子节点 IsSelected 变化 -> Child_PropertyChanged() -> 回写 DTO.IsMsgActived
// 这样可以不依赖 XAML EventTrigger减少 UI 侧的递归触发风险。
AttachNodeHandlers(SchTabTree);
}
/// <summary>
/// 订阅父节点集合的 PropertyChanged。
/// 注意:子节点当前仅用于显示,不处理其 PropertyChanged。
/// </summary>
private void AttachNodeHandlers(IEnumerable<LinSchTabNode> nodes)
{
if (nodes == null) return;
foreach (var n in nodes)
{
n.PropertyChanged -= Node_PropertyChanged;
n.PropertyChanged += Node_PropertyChanged;
if (n.Children != null && n.Children.Any())
{
foreach (var c in n.Children)
{
c.PropertyChanged -= Child_PropertyChanged;
c.PropertyChanged += Child_PropertyChanged;
}
}
}
}
/// <summary>
/// 父节点属性变更回调:当 IsSelected 变化时,统一交由 OnSelectSchTab() 处理单选与联动。
/// </summary>
private void Node_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(LinSchTabNode.IsSelected))
{
OnSelectSchTab(sender as LinSchTabNode);
}
}
/// <summary>
/// 子节点属性变更:当 IsSelected 变化时,回写对应 DTO.IsMsgActived。
/// 仅当其父节点为选中状态时允许写回CanEdit=true
/// </summary>
private void Child_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(LinMsgNode.IsSelected)) return;
if (_isUpdatingSelection) return;
try
{
_isUpdatingSelection = true;
var child = sender as LinMsgNode;
if (child == null) return;
// 查找父节点
var parent = SchTabTree?.FirstOrDefault(n => n.Children.Contains(child));
if (parent == null) return;
// 仅在父节点选中(可编辑)时回写 DTO
if (!parent.IsSelected || !child.CanEdit) return;
var dto = ListLINScheduleConfigDto?.FirstOrDefault(d =>
string.Equals(d.SchTabName ?? string.Empty, parent.SchTabName ?? string.Empty, StringComparison.Ordinal)
&& string.Equals(d.MsgName ?? string.Empty, child.MsgName ?? string.Empty, StringComparison.Ordinal)
&& d.MsgNameIndex == child.MsgNameIndex);
if (dto != null)
{
dto.IsMsgActived = child.IsSelected;
}
}
finally
{
_isUpdatingSelection = false;
}
}
private DelegateCommand<object> _GridSelectionChangedCmd;
/// <summary>
/// 选中行数据命令
/// </summary>
public DelegateCommand<object> GridSelectionChangedCmd
{
set
{
_GridSelectionChangedCmd = value;
}
get
{
if (_GridSelectionChangedCmd == null)
{
_GridSelectionChangedCmd = new DelegateCommand<object>((par) => GridSelectionChangedCmdMethod(par));
}
return _GridSelectionChangedCmd;
}
}
private void GridSelectionChangedCmdMethod(object par)
{
//先判断是否是正确的集合数据防止DataGrid的数据源刷新导致的触发事件
var Selecteddata = par as LINScheduleConfigDto;
if (Selecteddata != null)
{
CurSelectedItem = Selecteddata;
}
}
//OpCmd
private DelegateCommand<string> _OpCmd;
/// <summary>
/// 增加方法命令
/// </summary>
public DelegateCommand<string> OpCmd
{
set
{
_OpCmd = value;
}
get
{
if (_OpCmd == null)
{
_OpCmd = new DelegateCommand<string>((Par) => OpCmdCall(Par));
}
return _OpCmd;
}
}
private void OpCmdCall(string Par)
{
switch (Par)
{
// 禁止新增/删除:来自 LDF 的数据不允许变更
case "LoadSch":
//通过CAN驱动加载调度表
if (ListLINScheduleConfigDto != null && ListLINScheduleConfigDto.Count > 0)
{
var messageBoxResult = MessageBox.Show("检测到当前存在数据,下载后将要覆盖当前数据,请你确认?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Hand);
if (messageBoxResult == MessageBoxResult.OK)
{
LoadSch();
}
else
{
//不动作
}
}
else
{
LoadSch();
}
break;
default:
break;
}
}
/// <summary>
/// 加载调度表
/// </summary>
private void LoadSch()
{
var ListLINScheduleConfig = LinDriveService.ToomossLinDrive.GetLINScheduleConfigs();
ListLINScheduleConfigDto.Clear();
//先清空
FreeSql.Delete<LINScheduleConfig>()
.Where(a => a.CanLinConfigProId == SelectCanLinConfigProId)
.ExecuteAffrows();
foreach (var item in ListLINScheduleConfig)
{
ListLINScheduleConfigDto.Add(Mapper.Map<LINScheduleConfigDto>(item));
}
// 重新构建树
BuildTree();
}
private DelegateCommand saveCmd;
/// <summary>
/// 保存命令
/// </summary>
public DelegateCommand SaveCmd
{
set
{
saveCmd = value;
}
get
{
if (saveCmd == null)
{
saveCmd = new DelegateCommand(() => SaveCmdMethod());
}
return saveCmd;
}
}
/// <summary>
/// 保存命令方法
/// </summary>
/// <exception cref="NotImplementedException"></exception>
private void SaveCmdMethod()
{
//检查空的数据
foreach (var item in ListLINScheduleConfigDto)
{
if (string.IsNullOrEmpty(item.MsgName))
{
MessageBox.Show("请确认消息名称是否正确", "提示", MessageBoxButton.OK, MessageBoxImage.Hand);
return;
}
//if (item.Cycle == 0)
//{
// MessageBox.Show("请确认周期是否正确", "提示", MessageBoxButton.OK, MessageBoxImage.Hand);
// return;
//}
}
// 保存前:根据树中选中的调度表更新 DTO 的 IsActive确保只保留一个激活调度表
var activeNode = SchTabTree?.FirstOrDefault(n => n.IsSelected);
foreach (var dto in ListLINScheduleConfigDto)
{
dto.IsActive = activeNode != null && string.Equals(dto.SchTabName, activeNode.SchTabName, StringComparison.Ordinal);
}
// 保存前:将子节点的勾选状态写回 DTO.IsMsgActived
foreach (var parent in SchTabTree)
{
foreach (var child in parent.Children)
{
var dto = ListLINScheduleConfigDto.FirstOrDefault(d =>
string.Equals(d.SchTabName ?? string.Empty, parent.SchTabName ?? string.Empty, StringComparison.Ordinal)
&& string.Equals(d.MsgName ?? string.Empty, child.MsgName ?? string.Empty, StringComparison.Ordinal)
&& d.MsgNameIndex == child.MsgNameIndex);
if (dto != null)
{
dto.IsMsgActived = child.IsSelected;
}
}
}
//检查数据是否正常并持久化(结构来自 LDF不允许新增/删除,仅更新激活状态与周期等)
foreach (var item in ListLINScheduleConfigDto)
{
item.CanLinConfigProId = SelectCanLinConfigProId;
FreeSql.InsertOrUpdate<LINScheduleConfig>()
.SetSource(Mapper.Map<LINScheduleConfig>(item))
.ExecuteAffrows();
}
ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>(
Mapper.Map<List<LINScheduleConfigDto>>(FreeSql.Select<LINScheduleConfig>().Where(a => a.CanLinConfigProId == SelectCanLinConfigProId).ToList()));
// 重新构建树,反映保存结果
BuildTree();
DialogParameters pars = new DialogParameters
{
{ "ReturnValue", ListLINScheduleConfigDto }
};
RaiseRequestClose(new DialogResult(ButtonResult.OK, pars));
}
private DelegateCommand cancelCmd;
/// <summary>
/// 保存命令
/// </summary>
public DelegateCommand CancelCmd
{
set
{
cancelCmd = value;
}
get
{
if (cancelCmd == null)
{
cancelCmd = new DelegateCommand(() => CancelCmdMethod());
}
return cancelCmd;
}
}
/// <summary>
/// 取消命令方法
/// </summary>
/// <exception cref="NotImplementedException"></exception>
private void CancelCmdMethod()
{
RaiseRequestClose(new DialogResult(ButtonResult.Cancel));
}
/// <summary>
/// 窗口打开时的传递的参数
/// </summary>
/// <param name="parameters"></param>
public override void OnDialogOpened(IDialogParameters parameters)
{
ListMsg = parameters.GetValue<List<string>>("ListMsg");
// 转换为CbxItems集合都是文本内容
MsgCbxItems = new ObservableCollection<CbxItems>(
ListMsg.Select(value => new CbxItems
{
Key = value,
Text = value
}));
ListLINScheduleConfigDto = parameters.GetValue<ObservableCollection<LINScheduleConfigDto>>("ListLINScheduleConfigDto");
//防止返回的数据为空,就无法增加了
if (ListLINScheduleConfigDto == null) ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>();
//Name = parameters.GetValue<string>("Name");
SelectCanLinConfigProId = parameters.GetValue<long>("SelectCanLinConfigProId");
// 初次打开时构建树,并根据已有 IsActive 状态渲染
BuildTree();
}
}
}

View File

@@ -38,7 +38,7 @@ namespace CapMachine.Wpf.ViewModels
/// <param name="machineRtDataService"></param>
public LinConfigViewModel(IDialogService dialogService, IFreeSql freeSql,
IEventAggregator eventAggregator, IRegionManager regionManager, SysRunService sysRunService,
ConfigService configService, LinDriveService linDriveService, ComActionService comActionService,
ConfigService configService, LinDriveService linDriveService, ComActionService comActionService, LogicRuleService logicRuleService,
IMapper mapper, MachineRtDataService machineRtDataService)
{
//LogService = logService;
@@ -49,12 +49,24 @@ namespace CapMachine.Wpf.ViewModels
ConfigService = configService;
LinDriveService = linDriveService;
ComActionService = comActionService;
LogicRuleService = logicRuleService;
Mapper = mapper;
this.MachineRtDataService = machineRtDataService;
//MachineDataService = machineDataService;
DialogService = dialogService;
//数据波特率
DataBaudRateCbxItems = new ObservableCollection<CbxItems>()
{
new CbxItems(){ Key="38400",Text="38400"},
new CbxItems(){ Key="19200",Text="19200"},
new CbxItems(){ Key="14400",Text="14400"},
new CbxItems(){ Key="9600",Text="9600"},
new CbxItems(){ Key="4800",Text="4800"},
new CbxItems(){ Key="2400",Text="2400"},
};
WriteNameCbxItems = new ObservableCollection<CbxItems>()
{
new CbxItems(){ Key="转速",Text="转速"},
@@ -84,7 +96,8 @@ namespace CapMachine.Wpf.ViewModels
new CbxItems(){ Key="通讯PTC模块温度",Text="通讯PTC模块温度"},
};
InitLoadLinConfigPro();
//初始化写规则下拉框
InitWriteRuleCbx();
}
@@ -98,6 +111,7 @@ namespace CapMachine.Wpf.ViewModels
public ConfigService ConfigService { get; }
public LinDriveService LinDriveService { get; }
public ComActionService ComActionService { get; }
public LogicRuleService LogicRuleService { get; }
public IMapper Mapper { get; }
private MachineRtDataService MachineRtDataService { get; }
@@ -106,6 +120,49 @@ namespace CapMachine.Wpf.ViewModels
/// </summary>
public IDialogService DialogService { get; }
private ObservableCollection<CbxItems> _WriteRuleCbxItems;
/// <summary>
/// 写入的规格集合
/// </summary>
public ObservableCollection<CbxItems> WriteRuleCbxItems
{
get { return _WriteRuleCbxItems; }
set { _WriteRuleCbxItems = value; RaisePropertyChanged(); }
}
#region
/// <summary>
/// 逻辑更改事件
/// </summary>
/// <param name="msg"></param>
/// <exception cref="NotImplementedException"></exception>
private void LogicRuleChangeEventCall(string msg)
{
//InitWriteRuleCbx();
}
/// <summary>
/// 初始化写规则下拉框
/// </summary>
private void InitWriteRuleCbx()
{
WriteRuleCbxItems = new ObservableCollection<CbxItems>();
//选择的读写规则
foreach (var itemRule in LogicRuleService.LogicRuleDtos)
{
WriteRuleCbxItems.Add(new CbxItems()
{
Key = itemRule.Id.ToString(),
Text = itemRule.Name
});
}
}
#endregion
#region LinConfigPro
@@ -118,7 +175,8 @@ namespace CapMachine.Wpf.ViewModels
//LIN配置集合数据
canLinConfigPros = FreeSql.Select<CanLinConfigPro>().Where(a => a.CANLINInfo == CANLIN.LIN)
.Include(a => a.LINConfigExd)
.IncludeMany(a => a.CanLinConfigContents)
.IncludeMany(a => a.CanLinConfigContents, then => then.Include(b => b.LogicRule))
.IncludeMany(a => a.LinScheduleConfigs)
.ToList();
ListCanLinConfigPro = new ObservableCollection<CanLinConfigPro>(canLinConfigPros);
@@ -145,6 +203,7 @@ namespace CapMachine.Wpf.ViewModels
MsgName = item.MsgFrameName,
SignalName = item.SignalName,
SignalCmdValue = double.TryParse(item.DefautValue, out double result) == true ? result : 0,
LogicRuleDto = Mapper.Map<LogicRuleDto>(item.LogicRule),
});
//LinDriveService.CmdData.Add(new LinCmdData()
//{
@@ -156,11 +215,30 @@ namespace CapMachine.Wpf.ViewModels
}
}
else
{
ListWriteCanLinRWConfigDto = new ObservableCollection<CanLinRWConfigDto>();
}
var ReadData = SelectCanLinConfigPro.CanLinConfigContents!.Where(a => a.RWInfo == RW.Read).ToList();
if (ReadData != null && ReadData.Count > 0)
{
ListReadCanLinRWConfigDto = new ObservableCollection<CanLinRWConfigDto>(Mapper.Map<List<CanLinRWConfigDto>>(ReadData));
}
else
{
ListReadCanLinRWConfigDto = new ObservableCollection<CanLinRWConfigDto>();
}
//调度表配置信息
if (SelectCanLinConfigPro.LinScheduleConfigs != null && SelectCanLinConfigPro.LinScheduleConfigs.Count() > 0)
{
ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>(Mapper.Map<List<LINScheduleConfigDto>>(SelectCanLinConfigPro.LinScheduleConfigs));
}
else
{
ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>();
}
//匹配选中的SelectCanLinConfigPro.CanLinConfigContents和ListLinLdfModel
MatchSeletedAndLinLdfModel();
@@ -408,6 +486,8 @@ namespace CapMachine.Wpf.ViewModels
LinDriveService.InitLinConfig(SelectCanLinConfigPro);
InitLoadLinConfigPro();
// 订阅 CmdData 的数据变化事件,用于基于数据变化刷新调度表
LinDriveService.ToomossLinDrive.LoadCmdDataToDrive(LinDriveService.CmdData);
}
else
{
@@ -496,6 +576,7 @@ namespace CapMachine.Wpf.ViewModels
MsgName = item.MsgFrameName,
SignalName = item.SignalName,
SignalCmdValue = double.TryParse(item.DefautValue, out double result) == true ? result : 0,
LogicRuleDto = Mapper.Map<LogicRuleDto>(item.LogicRule),
});
//LinDriveService.CmdData.Add(new LinCmdData()
@@ -508,13 +589,33 @@ namespace CapMachine.Wpf.ViewModels
}
}
else
{
ListWriteCanLinRWConfigDto = new ObservableCollection<CanLinRWConfigDto>();
}
var ReadData = SelectCanLinConfigPro.CanLinConfigContents!.Where(a => a.RWInfo == RW.Read).ToList();
if (ReadData != null && ReadData.Count > 0)
{
ListReadCanLinRWConfigDto = new ObservableCollection<CanLinRWConfigDto>(Mapper.Map<List<CanLinRWConfigDto>>(ReadData));
}
else
{
ListReadCanLinRWConfigDto = new ObservableCollection<CanLinRWConfigDto>();
}
SelectCanLinConfigProConfigName = SelectCanLinConfigPro.ConfigName;
//调度表配置信息
if (SelectCanLinConfigPro.LinScheduleConfigs != null && SelectCanLinConfigPro.LinScheduleConfigs.Count() > 0)
{
ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>(Mapper.Map<List<LINScheduleConfigDto>>(SelectCanLinConfigPro.LinScheduleConfigs));
}
else
{
ListLINScheduleConfigDto = new ObservableCollection<LINScheduleConfigDto>();
}
return;
}
//先判断是否是正确的集合数据防止DataGrid的数据源刷新导致的触发事件
@@ -792,6 +893,58 @@ namespace CapMachine.Wpf.ViewModels
set { _SelectedLINConfigExdDto = value; RaisePropertyChanged(); }
}
private ObservableCollection<CbxItems> _DataBaudRateCbxItems;
/// <summary>
/// CAN 数据波特率
/// </summary>
public ObservableCollection<CbxItems> DataBaudRateCbxItems
{
get { return _DataBaudRateCbxItems; }
set { _DataBaudRateCbxItems = value; RaisePropertyChanged(); }
}
private DelegateCommand<object> _SchEnableCmd;
/// <summary>
/// 调度表的使能 操作的指令
/// </summary>
public DelegateCommand<object> SchEnableCmd
{
set
{
_SchEnableCmd = value;
}
get
{
if (_SchEnableCmd == null)
{
_SchEnableCmd = new DelegateCommand<object>((Par) => SchEnableCmdCall(Par));
}
return _SchEnableCmd;
}
}
/// <summary>
/// 调度表的使能信息
/// </summary>
/// <param name="par"></param>
/// <exception cref="NotImplementedException"></exception>
private void SchEnableCmdCall(object par)
{
var dd = SelectedLINConfigExdDto.SchEnable;
var Result = (bool)par;
if (Result)
{
LinDriveService.ToomossLinDrive.SchEnable = true;
}
else
{
LinDriveService.ToomossLinDrive.SchEnable = false;
}
}
private DelegateCommand<string> _LinOpCmd;
/// <summary>
/// LIN操作的指令
@@ -835,7 +988,7 @@ namespace CapMachine.Wpf.ViewModels
//系统使用了LIN
ConfigService.CanLinRunStateModel.CurSysSelectedCanLin = CanLinEnum.Lin;
}
//LIN LDF配置 有LDF配置的话则直接加载LDF信息
if (!string.IsNullOrEmpty(SelectCanLinConfigPro.LINConfigExd.LdfPath))
{
@@ -877,6 +1030,7 @@ namespace CapMachine.Wpf.ViewModels
.Set(a => a.LdfPath, SelectedLINConfigExdDto.LdfPath)
.Set(a => a.Cycle, SelectedLINConfigExdDto.Cycle)
.Set(a => a.BaudRate, SelectedLINConfigExdDto.BaudRate)
.Set(a => a.SchEnable, SelectedLINConfigExdDto.SchEnable)
.Where(a => a.Id == SelectedLINConfigExdDto.Id)
.ExecuteUpdated();
}
@@ -938,6 +1092,12 @@ namespace CapMachine.Wpf.ViewModels
break;
case "CycleSend"://循环发送你
//有可能加载完毕后不手动改变状态,导致值没有传输,所以这里赋值
LinDriveService.ToomossLinDrive.SchEnable = SelectedLINConfigExdDto.SchEnable;
//无论有没有调度表都要把这个配置给LinDriveService
LinDriveService.ListLINScheduleConfig = ListLINScheduleConfigDto.ToList();
//循环发送数据
LinDriveService.CycleSendMsg();
@@ -992,6 +1152,17 @@ namespace CapMachine.Wpf.ViewModels
}
private ObservableCollection<LINScheduleConfigDto> _ListLINScheduleConfigDto;
/// <summary>
///调度表集合
/// </summary>
public ObservableCollection<LINScheduleConfigDto> ListLINScheduleConfigDto
{
get { return _ListLINScheduleConfigDto; }
set { _ListLINScheduleConfigDto = value; RaisePropertyChanged(); }
}
//private string _SelectedWriteName;
///// <summary>
///// 选中的写入的Name
@@ -1106,6 +1277,7 @@ namespace CapMachine.Wpf.ViewModels
//直接修改
FreeSql.Update<CanLinRWConfig>(item.Id)
.Set(a => a.Name, item.Name)
.Set(a => a.LogicRuleId, item.LogicRuleId)
.Set(a => a.DefautValue, item.DefautValue)
.ExecuteAffrows();
//ListWriteCanLinRWConfigDto.Remove(SelectedWriteCanLinRWConfigDto);
@@ -1117,8 +1289,6 @@ namespace CapMachine.Wpf.ViewModels
InitLoadLinConfigPro();
}
break;
case "Delete":
if (SelectedWriteCanLinRWConfigDto != null)
@@ -1136,6 +1306,47 @@ namespace CapMachine.Wpf.ViewModels
System.Windows.MessageBox.Show("请选中后再进行【删除】操作?", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Hand);
}
break;
case "WriteSch"://调度表
//LinDriveService.ToomossLinDrive.LinTest();
//LinDriveService.ToomossLinDrive.StartSchedule();
//break;
//
if (LinDriveService.ToomossLinDrive.OpenState)
{
//弹窗
DialogService.ShowDialog("DialogLINSchConfigView", new DialogParameters() {
{"ListMsg", LinDriveService.CmdData.GroupBy(a=>a.MsgName).Select(a=>a.Key).ToList() },
{ "ListLINScheduleConfigDto",ListLINScheduleConfigDto},
{ "SelectCanLinConfigProId",SelectCanLinConfigPro.Id},
}, (par) =>
{
if (par.Result == ButtonResult.OK)
{
////程序名称
ListLINScheduleConfigDto = par.Parameters.GetValue<ObservableCollection<LINScheduleConfigDto>>("ReturnValue");
//把更新后的最新值给当前的主集合中
SelectCanLinConfigPro.LinScheduleConfigs = Mapper.Map<List<LINScheduleConfig>>(ListLINScheduleConfigDto.ToList());
}
else if (par.Result == ButtonResult.Cancel)
{
//取消
}
});
}
else
{
System.Windows.MessageBox.Show("未发现写入的执行的命令数据,无法配置?", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Hand);
}
break;
default:
break;

View File

@@ -0,0 +1,109 @@
using Prism.Mvvm;
using System.Collections.ObjectModel;
namespace CapMachine.Wpf.ViewModels
{
/// <summary>
/// 调度表节点(父节点)。
/// 与 XAML 中父级 <TreeView> 的 <HierarchicalDataTemplate> 绑定:
/// - 显示字段:<see cref="SchTabName"/>
/// - 选择字段:<see cref="IsSelected"/>TwoWay 绑定至 CheckBox
/// - 子集合:<see cref="Children"/>(用于展开显示消息/帧子节点)
///
/// 使用 Prism 的 <see cref="BindableBase.SetProperty{T}(ref T, T, string?)"/>
/// 以避免值未发生变化时重复触发 PropertyChanged 引起的联动递归。
/// </summary>
public class LinSchTabNode : BindableBase
{
/// <summary>
/// 调度表名称(父节点标题)。
/// </summary>
private string _SchTabName;
public string SchTabName
{
get => _SchTabName;
set => SetProperty(ref _SchTabName, value);
}
private bool _IsSelected;
/// <summary>
/// 是否被激活/选中(父节点单选)。
/// 该属性与 XAML 中父节点的 CheckBox 进行 TwoWay 绑定,
/// 其变更由 ViewModel 监听并处理“单选联动”和“子节点跟随”。
/// </summary>
public bool IsSelected
{
get => _IsSelected;
set => SetProperty(ref _IsSelected, value);
}
/// <summary>
/// 子节点集合(消息/帧条目)。
/// </summary>
private ObservableCollection<LinMsgNode> _Children = new ObservableCollection<LinMsgNode>();
public ObservableCollection<LinMsgNode> Children
{
get => _Children;
set => SetProperty(ref _Children, value);
}
}
/// <summary>
/// 消息/帧 节点(子节点)。
/// 与 XAML 中父级 <HierarchicalDataTemplate.ItemTemplate> 绑定:
/// - 显示字段:<see cref="MsgName"/> / <see cref="MsgNameIndex"/>
/// - 选择字段:<see cref="IsSelected"/>(当前设计作为“显示联动”,非编辑入口)
/// </summary>
public class LinMsgNode : BindableBase
{
/// <summary>
/// 所属的调度表名称(便于回写 DTO 时定位)。
/// </summary>
private string _SchTabName;
public string SchTabName
{
get => _SchTabName;
set => SetProperty(ref _SchTabName, value);
}
/// <summary>
/// 消息/帧名称。
/// </summary>
private string _MsgName;
public string MsgName
{
get => _MsgName;
set => SetProperty(ref _MsgName, value);
}
/// <summary>
/// 消息/帧 Index。
/// </summary>
private int _MsgNameIndex;
public int MsgNameIndex
{
get => _MsgNameIndex;
set => SetProperty(ref _MsgNameIndex, value);
}
private bool _IsSelected;
/// <summary>
/// 是否被选中(随父节点联动显示)。
/// </summary>
public bool IsSelected
{
get => _IsSelected;
set => SetProperty(ref _IsSelected, value);
}
/// <summary>
/// 子节点勾选是否可用(仅当父调度表被选中时可编辑)。
/// </summary>
private bool _CanEdit;
public bool CanEdit
{
get => _CanEdit;
set => SetProperty(ref _CanEdit, value);
}
}
}

View File

@@ -0,0 +1,210 @@
<UserControl
x:Class="CapMachine.Wpf.Views.DialogLINSchConfigView"
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:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:local="clr-namespace:CapMachine.Wpf.Views"
xmlns:localEx="clr-namespace:CapMachine.Wpf"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prism="http://prismlibrary.com/"
xmlns:vm="clr-namespace:CapMachine.Wpf.ViewModels"
Width="1000"
Height="800"
mc:Ignorable="d">
<UserControl.Resources>
<localEx:BindingProxy x:Key="Proxy" Data="{Binding}" />
<Style x:Key="myHeaderStyle" TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="FontSize" Value="24" />
<Setter Property="Width" Value="218" />
</Style>
<Style x:Key="myHeaderStyle1" TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="FontSize" Value="16" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<!--<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<Button
Margin="10,0"
Command="{Binding OpCmd}"
CommandParameter="Add"
FontWeight="Bold"
Foreground="#404040"
Style="{StaticResource MaterialDesignFlatAccentBgButton}">
<StackPanel Orientation="Horizontal">
<TextBlock
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="14"
Foreground="#404040"
Text="&#xe8c0; " />
<TextBlock
VerticalAlignment="Center"
FontSize="14"
Text="新增" />
</StackPanel>
</Button>
-->
<!--<Button
Margin="10,0"
Command="{Binding CopyCmd}"
FontWeight="Bold"
Foreground="#404040"
Style="{StaticResource MaterialDesignFlatAccentBgButton}">
<StackPanel Orientation="Horizontal">
<TextBlock
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="14"
Foreground="#404040"
Text="&#xe9c6;" />
<TextBlock
VerticalAlignment="Center"
FontSize="14"
Text="复制" />
</StackPanel>
</Button>-->
<!--
<Button
Margin="10,0"
Command="{Binding OpCmd}"
CommandParameter="Delete"
FontWeight="Bold"
Foreground="#404040"
Style="{StaticResource MaterialDesignFlatAccentBgButton}">
<StackPanel Orientation="Horizontal">
<TextBlock
Margin="0,0,5,0"
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="14"
Foreground="#404040"
Text="&#xe9d9;" />
<TextBlock
VerticalAlignment="Center"
FontSize="14"
Text="删除" />
</StackPanel>
</Button>
</StackPanel>-->
<StackPanel
Margin="30,0"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Margin="10,0"
Command="{Binding OpCmd}"
CommandParameter="LoadSch"
FontWeight="Bold"
Foreground="Green"
Style="{StaticResource MaterialDesignFlatAccentBgButton}">
<StackPanel Orientation="Horizontal">
<TextBlock
Margin="0,0,5,0"
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="14"
Foreground="Green"
Text="&#xe63b;" />
<TextBlock
VerticalAlignment="Center"
FontSize="14"
Text="下载" />
</StackPanel>
</Button>
<!--<TextBlock
Margin="10,0,5,0"
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="22"
Text="&#xe9ff;" />
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20"
Text="报文发送方式:"
TextAlignment="Center" />
<ComboBox
Width="120"
DisplayMemberPath="Text"
FontSize="20"
ItemsSource="{Binding SendOrderCbxItems}"
SelectedValue="{Binding CurSendOrder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Key" />-->
</StackPanel>
<Grid Grid.Row="1">
<Border
Margin="5"
Padding="6"
BorderBrush="#D0D0D0"
BorderThickness="1"
CornerRadius="4">
<TreeView ItemsSource="{Binding SchTabTree}">
<TreeView.ItemTemplate>
<!-- 父节点模板:不使用 DataType避免类型解析 -->
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text=" " />
<TextBlock
FontSize="20"
FontWeight="Bold"
Text="{Binding SchTabName}" />
</StackPanel>
<!-- 子节点模板:文本显示 -->
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center" Orientation="Horizontal">
<CheckBox
Margin="0,0,6,0"
VerticalAlignment="Center"
IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding CanEdit}" />
<TextBlock
VerticalAlignment="Center"
FontSize="16"
Foreground="DimGray">
<Run Text="{Binding MsgName}" />
<Run Text=" (Index: " />
<Run Text="{Binding MsgNameIndex}" />
<Run Text=")" />
</TextBlock>
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Border>
</Grid>
<StackPanel
Grid.Row="2"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Margin="10,10"
Command="{Binding SaveCmd}"
Content="确定"
Foreground="White" />
<Button
Margin="10,0"
Command="{Binding CancelCmd}"
Content="取消"
Foreground="White" />
</StackPanel>
</Grid>
</UserControl>

View File

@@ -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 CapMachine.Wpf.Views
{
/// <summary>
/// DialogLINSchConfigView.xaml 的交互逻辑
/// </summary>
public partial class DialogLINSchConfigView : UserControl
{
public DialogLINSchConfigView()
{
InitializeComponent();
}
}
}

View File

@@ -406,7 +406,14 @@
FontSize="18"
Text="&#xe9f8;" />
<TextBlock Style="{StaticResource TextBlockStyle}" Text="波特率" />
<TextBox Style="{StaticResource TextBoxStyle}" Text="{Binding SelectedLINConfigExdDto.BaudRate}" />
<ComboBox
Width="100"
DisplayMemberPath="Text"
FontSize="16"
ItemsSource="{Binding DataBaudRateCbxItems}"
SelectedValue="{Binding SelectedLINConfigExdDto.BaudRate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Key" />
<!--<TextBox Style="{StaticResource TextBoxStyle}" Text="{Binding SelectedLINConfigExdDto.BaudRate}" />-->
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal">
@@ -573,6 +580,84 @@
</StackPanel>
<StackPanel
Grid.Row="1"
Grid.Column="1"
Margin="-20,0"
Orientation="Horizontal">
<TextBlock
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="20"
Text="&#xe977;" />
<TextBlock
Width="80"
Style="{StaticResource TextBlockStyle}"
Text="报文状态:" />
<Border
Margin="0,12"
BorderThickness="1"
CornerRadius="5">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="Gray" />
<Style.Triggers>
<DataTrigger Binding="{Binding LinDriveService.ToomossLinDrive.IsSendOk}" Value="true">
<Setter Property="Background" Value="LimeGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock
Margin="5"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="White"
Text="发送" />
</Border>
<Border
Margin="2,12"
BorderThickness="1"
CornerRadius="5">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="Gray" />
<Style.Triggers>
<DataTrigger Binding="{Binding LinDriveService.ToomossLinDrive.IsReviceOk}" Value="true">
<Setter Property="Background" Value="LimeGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock
Margin="5"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="White"
Text="接收" />
</Border>
<TextBlock
Margin="5,0,0,0"
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="20"
Text="&#xe796;" />
<TextBlock
Width="90"
Style="{StaticResource TextBlockStyle}"
Text="启用调度表:" />
<ToggleButton
Width="40"
Margin="5,2"
Command="{Binding SchEnableCmd}"
CommandParameter="{Binding SelectedLINConfigExdDto.SchEnable}"
IsChecked="{Binding SelectedLINConfigExdDto.SchEnable}"
Style="{StaticResource MaterialDesignSwitchToggleButton}"
ToolTip="启用调度表" />
</StackPanel>
</Grid>
</Grid>
@@ -631,6 +716,24 @@
Margin="0,0,15,0"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Margin="5,0"
Command="{Binding WriteCmd}"
CommandParameter="WriteSch"
Foreground="White">
<StackPanel Orientation="Horizontal">
<TextBlock
Margin="2,0"
VerticalAlignment="Center"
FontFamily="/Assets/Fonts/#iconfont"
FontSize="18"
Text="&#xe796;" />
<TextBlock
VerticalAlignment="Center"
FontSize="14"
Text="调度表" />
</StackPanel>
</Button>
<Button
Margin="5,0"
Command="{Binding WriteCmd}"
@@ -710,13 +813,26 @@
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding DefautValue}">
<DataGridTextColumn.Header>
<TextBlock FontWeight="Bold" Text="默认值" />
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTemplateColumn Width="200" Header="规则名称">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
DisplayMemberPath="Text"
ItemsSource="{Binding Source={StaticResource Proxy}, Path=Data.WriteRuleCbxItems}"
SelectedValue="{Binding LogicRuleId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Key" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<prism:InvokeCommandAction Command="{Binding WriteGridSelectionChangedCmd}" CommandParameter="{Binding ElementName=LINWriteDatagrid, Path=SelectedItem}" />