CommBatchNodes.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Threading;
  6. using PropertyGridLib.Attributes;
  7. using PropertyGridLib.Controls;
  8. using TeamAAS.Communication;
  9. using TeamAAS.Core;
  10. using TeamAAS.Communication.Interfaces;
  11. using TeamAAS.FlowEditor.Execution;
  12. using TeamAAS.FlowEditor.Models;
  13. using TeamAAS.FlowEditor.Plugins;
  14. using TeamAAS.FlowEngine.FormulaData;
  15. using Plugins.Standard.Models;
  16. namespace Plugins.Standard.Models
  17. {
  18. // ─────────────────────────────────────────────────────────────────────
  19. // 通讯标准节点模型(批量读 / 批量写)。
  20. // 设计要点:一个节点一次事务处理整组点位 —— 减少往返、结果按键值输出、
  21. // 失败逐项报告(哪一项失败不影响其余项的执行与结果记录)。
  22. // ─────────────────────────────────────────────────────────────────────
  23. /// <summary>通讯批量读取节点模型。</summary>
  24. [Serializable]
  25. public class CommBatchReadModel : BasePluginModel
  26. {
  27. [Category("I.设备")]
  28. [DisplayName("1.通讯设备名")]
  29. [Description("通讯管理器中配置的设备名称(须与名称完全一致)")]
  30. public string DeviceName { get; set; } = "";
  31. [Category("II.读取项")]
  32. [DisplayName("1.读取列表")]
  33. [Description("地址→键名 映射列表;运行后每个键名成为本节点输出(下游用 &{本节点.键名} 绑定)")]
  34. [CollectionEditor(CanAdd = true, CanRemove = true, CanSort = true)]
  35. public List<CommReadItem> Items { get; set; } = new List<CommReadItem>();
  36. [Category("III.选项")]
  37. [DisplayName("1.失败时整体失败")]
  38. [Description("开=任一项读取失败则节点 Failed;关=失败项记入 错误项 输出但节点仍成功")]
  39. public bool FailOnAnyError { get; set; } = false;
  40. }
  41. /// <summary>批量读取项:设备地址 → 输出键名。</summary>
  42. [Serializable]
  43. public class CommReadItem
  44. {
  45. [Category("读取项")]
  46. [DisplayName("1.地址")]
  47. [Description("设备地址(DB块/寄存器/Tag,随设备类型解释)")]
  48. public string Address { get; set; } = "";
  49. [Category("读取项")]
  50. [DisplayName("2.键名")]
  51. [Description("输出键名(下游绑定的名字)")]
  52. public string Key { get; set; } = "";
  53. public override string ToString() => string.IsNullOrWhiteSpace(Key) ? Address : $"{Key} ← {Address}";
  54. }
  55. /// <summary>通讯批量写入节点模型。</summary>
  56. [Serializable]
  57. public class CommBatchWriteModel : BasePluginModel
  58. {
  59. [Category("I.设备")]
  60. [DisplayName("1.通讯设备名")]
  61. [Description("通讯管理器中配置的设备名称(须与名称完全一致)")]
  62. public string DeviceName { get; set; } = "";
  63. [Category("II.写入项")]
  64. [DisplayName("1.写入列表")]
  65. [Description("地址←来源值 映射列表;来源值可绑定上游输出公式(如 &{检测结果.面积})")]
  66. [CollectionEditor(CanAdd = true, CanRemove = true, CanSort = true)]
  67. public List<CommWriteItem> Items { get; set; } = new List<CommWriteItem>();
  68. [Category("III.选项")]
  69. [DisplayName("1.失败时整体失败")]
  70. [Description("开=任一项写入失败则节点 Failed;关=失败项记入 错误项 输出但节点仍成功")]
  71. public bool FailOnAnyError { get; set; } = true;
  72. }
  73. /// <summary>批量写入项:目标地址 ← 来源值(公式/常量)。</summary>
  74. [Serializable]
  75. public class CommWriteItem
  76. {
  77. public CommWriteItem()
  78. {
  79. Source = new FormulaBound<object>();
  80. }
  81. [Category("写入项")]
  82. [DisplayName("1.地址")]
  83. [Description("设备地址(DB块/寄存器/Tag,随设备类型解释)")]
  84. public string Address { get; set; } = "";
  85. [Category("写入项")]
  86. [DisplayName("2.来源值")]
  87. [Description("要写入的值;可绑定上游输出(&{节点.键})或填常量")]
  88. [FormulaEditor(typeof(PluginDataProvider))]
  89. public FormulaBound<object> Source { get; set; }
  90. public override string ToString() => $"{Address} ← {Source?.Formula ?? Source?.Value?.ToString() ?? ""}";
  91. }
  92. }
  93. namespace Plugins.Standard
  94. {
  95. // ─────────────────────────────────────────────────────────────────────
  96. // 通讯标准节点(批量读 / 批量写)。
  97. // 参考 VisionKit 的通讯节点形态并按 TeamAAS 节点契约实现;后续优化方向:
  98. // - 支持 PLC 适配层一次事务批量读写(当前逐项调用 ICommunication.Read/WriteValue);
  99. // - 地址解析缓存与自动重连重试。
  100. // ─────────────────────────────────────────────────────────────────────
  101. /// <summary>批量读取:一次执行读取整组地址,结果按键名输出,失败项逐条记录。</summary>
  102. [Serializable]
  103. [Plugin("批量读取", PluginCategory.通讯模块, typeof(CommBatchReadModel), "Download",
  104. NodeShape = NodeCategory.Normal,
  105. Description = "通讯批量读取:一次事务读取整组地址,结果按键名输出;逐项错误报告,可用公式绑定设备名")]
  106. public class CommBatchReadPlugin : BasePlugin<CommBatchReadModel>
  107. {
  108. public override List<OutputField> DeclareOutputs()
  109. {
  110. var list = new List<OutputField>
  111. {
  112. new OutputField("成功项数", typeof(int)),
  113. new OutputField("错误项数", typeof(int)),
  114. new OutputField("结果", typeof(bool)),
  115. };
  116. var items = Model?.Items ?? new List<Plugins.Standard.Models.CommReadItem>();
  117. foreach (var item in items)
  118. {
  119. if (item == null || string.IsNullOrWhiteSpace(item.Key)) continue;
  120. list.Add(new OutputField(item.Key, typeof(object)));
  121. }
  122. return list;
  123. }
  124. public override NodeRunStatus PluginRun(CancellationToken token, out Dictionary<string, object> results)
  125. {
  126. var res = new Dictionary<string, object>();
  127. results = res;
  128. NodeRunStatus Fail(string m) { res["Error"] = m; res["结果"] = false; Log(1, $"批量读取失败: {m}", TeamAAS.LogLevel.Error); return NodeRunStatus.Failed; }
  129. ICommunication device = FindDevice(Model.DeviceName);
  130. if (device == null) return Fail($"找不到通讯设备: {Model.DeviceName}");
  131. if (!device.IsConnected)
  132. {
  133. Log(3, "设备未连接,尝试连接…");
  134. try { device.Connect(); } catch (Exception ex) { return Fail($"设备连接失败: {ex.Message}"); }
  135. if (!device.IsConnected) return Fail("设备连接失败(无法建立连接)");
  136. }
  137. int ok = 0, err = 0;
  138. var errors = new List<string>();
  139. foreach (var item in Model.Items ?? new List<Plugins.Standard.Models.CommReadItem>())
  140. {
  141. if (token.IsCancellationRequested) return Fail("已取消");
  142. if (item == null || string.IsNullOrWhiteSpace(item.Address)) continue;
  143. var key = string.IsNullOrWhiteSpace(item.Key) ? item.Address : item.Key;
  144. try
  145. {
  146. res[key] = device.ReadValue(item.Address);
  147. ok++;
  148. Log(4, $"读取[{item.Address}] → {key} = {res[key]}");
  149. }
  150. catch (Exception ex)
  151. {
  152. err++;
  153. errors.Add($"{key}({item.Address}): {ex.Message}");
  154. res[key] = null;
  155. Log(2, $"读取失败[{item.Address}]: {ex.Message}", TeamAAS.LogLevel.Warning);
  156. }
  157. }
  158. res["成功项数"] = ok;
  159. res["错误项数"] = err;
  160. if (errors.Count > 0) res["错误项"] = string.Join("; ", errors);
  161. res["结果"] = err == 0 || !Model.FailOnAnyError;
  162. if (err > 0 && Model.FailOnAnyError)
  163. {
  164. Log(1, $"批量读取有 {err} 项失败: {string.Join("; ", errors)}", TeamAAS.LogLevel.Error);
  165. return NodeRunStatus.Failed;
  166. }
  167. Log(2, $"批量读取完成:成功 {ok} 项,失败 {err} 项");
  168. return NodeRunStatus.Success;
  169. }
  170. internal static ICommunication FindDevice(string name)
  171. {
  172. if (string.IsNullOrWhiteSpace(name)) return null;
  173. return CoreManager.Communication?.GetByName(name);
  174. }
  175. }
  176. /// <summary>批量写入:一次执行写入整组地址(来源可绑定公式),失败项逐条记录。</summary>
  177. [Serializable]
  178. [Plugin("批量写入", PluginCategory.通讯模块, typeof(CommBatchWriteModel), "Upload",
  179. NodeShape = NodeCategory.Normal,
  180. Description = "通讯批量写入:一次事务写入整组地址(来源绑定公式/常量);逐项错误报告")]
  181. public class CommBatchWritePlugin : BasePlugin<CommBatchWriteModel>
  182. {
  183. public override List<OutputField> DeclareOutputs() => new List<OutputField>
  184. {
  185. new OutputField("成功项数", typeof(int)),
  186. new OutputField("错误项数", typeof(int)),
  187. new OutputField("结果", typeof(bool)),
  188. };
  189. public override NodeRunStatus PluginRun(CancellationToken token, out Dictionary<string, object> results)
  190. {
  191. var res = new Dictionary<string, object>();
  192. results = res;
  193. NodeRunStatus Fail(string m) { res["Error"] = m; res["结果"] = false; Log(1, $"批量写入失败: {m}", TeamAAS.LogLevel.Error); return NodeRunStatus.Failed; }
  194. ICommunication device = CommBatchReadPlugin.FindDevice(Model.DeviceName);
  195. if (device == null) return Fail($"找不到通讯设备: {Model.DeviceName}");
  196. if (!device.IsConnected)
  197. {
  198. Log(3, "设备未连接,尝试连接…");
  199. try { device.Connect(); } catch (Exception ex) { return Fail($"设备连接失败: {ex.Message}"); }
  200. if (!device.IsConnected) return Fail("设备连接失败(无法建立连接)");
  201. }
  202. int ok = 0, err = 0;
  203. var errors = new List<string>();
  204. foreach (var item in Model.Items ?? new List<Plugins.Standard.Models.CommWriteItem>())
  205. {
  206. if (token.IsCancellationRequested) return Fail("已取消");
  207. if (item == null || string.IsNullOrWhiteSpace(item.Address)) continue;
  208. object value;
  209. try
  210. {
  211. value = !string.IsNullOrWhiteSpace(item.Source?.Formula)
  212. ? RegistryOrDebug.ResolveFormula(GetModel.FlowId, item.Source.Formula)
  213. : item.Source?.Value;
  214. }
  215. catch (Exception ex)
  216. {
  217. err++;
  218. errors.Add($"{item.Address}: 公式解析失败 {ex.Message}");
  219. continue;
  220. }
  221. try
  222. {
  223. device.WriteValue(item.Address, value);
  224. ok++;
  225. Log(4, $"写入[{item.Address}] ← {value}");
  226. }
  227. catch (Exception ex)
  228. {
  229. err++;
  230. errors.Add($"{item.Address}: {ex.Message}");
  231. Log(2, $"写入失败[{item.Address}]: {ex.Message}", TeamAAS.LogLevel.Warning);
  232. }
  233. }
  234. res["成功项数"] = ok;
  235. res["错误项数"] = err;
  236. if (errors.Count > 0) res["错误项"] = string.Join("; ", errors);
  237. res["结果"] = err == 0 || !Model.FailOnAnyError;
  238. if (err > 0 && Model.FailOnAnyError)
  239. {
  240. Log(1, $"批量写入有 {err} 项失败: {string.Join("; ", errors)}", TeamAAS.LogLevel.Error);
  241. return NodeRunStatus.Failed;
  242. }
  243. Log(2, $"批量写入完成:成功 {ok} 项,失败 {err} 项");
  244. return NodeRunStatus.Success;
  245. }
  246. }
  247. }