终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

364 lines
17 KiB

  1. using BPASmartClient.CustomResource.Pages.Model;
  2. using BPASmartClient.DosingSystem.ViewModel;
  3. using BPASmartClient.Modbus;
  4. using BPASmartClient.Model;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.Linq;
  10. using System.Net.NetworkInformation;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using BPA.Helper;
  14. using System.Text.RegularExpressions;
  15. namespace BPASmartClient.DosingSystem
  16. {
  17. public class DeviceInquire
  18. {
  19. private volatile static DeviceInquire _Instance;
  20. public static DeviceInquire GetInstance => _Instance ?? (_Instance = new DeviceInquire());
  21. private DeviceInquire() { }
  22. string IPSegment = "192.168.0.";
  23. ConcurrentDictionary<string, DeviceStatus> DeviceLists = new ConcurrentDictionary<string, DeviceStatus>();
  24. List<string> InvalidIP = new List<string>();//无效 IP 集合
  25. List<string> IPLists = new List<string>();//启动 Ping 任务IP集合
  26. ConcurrentQueue<string> IPQueues = new ConcurrentQueue<string>();//pincomplete 完成队列
  27. public ObservableCollection<DeviceCurrentStatus> TopDeviceCurrentStatuses { get; set; } = new ObservableCollection<DeviceCurrentStatus>();
  28. public ObservableCollection<DeviceCurrentStatus> BottomDeviceCurrentStatuses { get; set; } = new ObservableCollection<DeviceCurrentStatus>();
  29. public ObservableCollection<Devices> devices { get; set; } = new ObservableCollection<Devices>();
  30. private void DeviceDataInit()
  31. {
  32. ThreadManage.GetInstance().StartLong(new Action(() =>
  33. {
  34. for (int i = 0; i < DeviceLists.Count; i++)
  35. {
  36. string deviceName = DeviceLists.ElementAt(i).Value.DeviceName;
  37. int TopIndex = Array.FindIndex(TopDeviceCurrentStatuses.ToArray(), p => p.DeviceName == deviceName);
  38. int BottomIndex = Array.FindIndex(BottomDeviceCurrentStatuses.ToArray(), p => p.DeviceName == deviceName);
  39. if (TopIndex >= 0 && TopIndex < TopDeviceCurrentStatuses.Count)
  40. {
  41. TopDeviceCurrentStatuses.ElementAt(TopIndex).Weight = DeviceLists.ElementAt(i).Value.deviceStatus.WeightFeedback;
  42. TopDeviceCurrentStatuses.ElementAt(TopIndex).DeviceNum = DeviceLists.ElementAt(i).Value.deviceStatus.DeviceNum;
  43. }
  44. if (BottomIndex >= 0 && BottomIndex < BottomDeviceCurrentStatuses.Count)
  45. {
  46. BottomDeviceCurrentStatuses.ElementAt(BottomIndex).Weight = DeviceLists.ElementAt(i).Value.deviceStatus.WeightFeedback;
  47. BottomDeviceCurrentStatuses.ElementAt(BottomIndex).DeviceNum = DeviceLists.ElementAt(i).Value.deviceStatus.DeviceNum;
  48. }
  49. int deviceIndex = Array.FindIndex(devices.ToArray(), p => p.IpAddress == DeviceLists.ElementAt(i).Key/* && p.DeviceName != DeviceLists.ElementAt(i).Value.DeviceName && p.DeviceNum != DeviceLists.ElementAt(i).Value.deviceStatus.DeviceNum*/);
  50. if (deviceIndex >= 0 && deviceIndex < devices.Count)
  51. {
  52. devices.ElementAt(deviceIndex).DeviceName = DeviceLists.ElementAt(i).Value.DeviceName;
  53. devices.ElementAt(deviceIndex).DeviceNum = DeviceLists.ElementAt(i).Value.deviceStatus.DeviceNum;
  54. }
  55. }
  56. Thread.Sleep(200);
  57. }), "设备状态监听");
  58. }
  59. private void TestData()
  60. {
  61. for (int i = 0; i < 8; i++)
  62. {
  63. DeviceLists.TryAdd($"192.168.1.{i + 1}", new DeviceStatus() { DeviceName = $"测试设备{i + 1}" });
  64. TopDeviceCurrentStatuses.Add(new DeviceCurrentStatus()
  65. {
  66. DeviceName = $"测试设备{i + 1}",
  67. DeviceNum = i + 1,
  68. Weight = new Random().Next(100, 10000) / 100.0
  69. });
  70. Global.DeviceRawMaterials.Add(new RawMaterialModel()
  71. {
  72. DeviceIp = $"192.168.1.{i + 1}",
  73. RawMaterialName = $"测试设备{i + 1}",
  74. });
  75. devices.Add(new Devices()
  76. {
  77. DeviceName = $"测试设备{i + 1}",
  78. DeviceNum = i + 1,
  79. IpAddress = $"192.168.1.{i + 1}",
  80. });
  81. }
  82. for (int i = 8; i < 16; i++)
  83. {
  84. DeviceLists.TryAdd($"192.168.1.{i + 1}", new DeviceStatus() { DeviceName = $"测试设备{i + 1}" });
  85. BottomDeviceCurrentStatuses.Add(new DeviceCurrentStatus()
  86. {
  87. DeviceName = $"测试设备{i + 1}",
  88. DeviceNum = i + 1,
  89. Weight = new Random().Next(100, 10000) / 100.0
  90. });
  91. Global.DeviceRawMaterials.Add(new RawMaterialModel()
  92. {
  93. DeviceIp = $"192.168.1.{i + 1}",
  94. RawMaterialName = $"测试设备{i + 1}",
  95. });
  96. devices.Add(new Devices()
  97. {
  98. DeviceName = $"测试设备{i + 1}",
  99. DeviceNum = i + 1,
  100. IpAddress = $"192.168.1.{i + 1}",
  101. });
  102. }
  103. }
  104. public void Init()
  105. {
  106. if (!string.IsNullOrEmpty(Json<DevicePar>.Data.BaseParModel.NetworkSegAddress)) IPSegment = Json<DevicePar>.Data.BaseParModel.NetworkSegAddress;
  107. else Json<DevicePar>.Data.BaseParModel.NetworkSegAddress = IPSegment;
  108. //TestData();
  109. IpAddressLines();
  110. SiemensDevice.GetInstance.Connect(Json<DevicePar>.Data.BaseParModel.DeviceAddress);
  111. DeviceDataInit();
  112. ThreadManage.GetInstance().StartLong(new Action(() =>
  113. {
  114. if (IPQueues.Count >= IPLists.Count)
  115. IpAddressLines();
  116. Thread.Sleep(5000);
  117. }), "配料机设备上线监听", true);
  118. }
  119. public void Rescan()
  120. {
  121. InvalidIP.Clear();
  122. }
  123. public DeviceStatus GetDevice(string ip)
  124. {
  125. if (ip != null)
  126. {
  127. if (DeviceLists.ContainsKey(ip)) return DeviceLists[ip];
  128. else return new DeviceStatus();
  129. //var res = DeviceLists.Values.FirstOrDefault(p => p.IpAddress == ip);
  130. //if (res != null) return res;
  131. }
  132. return new DeviceStatus();
  133. }
  134. public List<DeviceStatus> GetDevice()
  135. {
  136. List<DeviceStatus> deviceStatuses = new List<DeviceStatus>();
  137. foreach (var device in DeviceLists)
  138. {
  139. deviceStatuses.Add(device.Value);
  140. }
  141. return deviceStatuses;
  142. }
  143. private void IpAddressLines()
  144. {
  145. IPLists.Clear();
  146. IPQueues.Clear();
  147. for (int i = 1; i <= 255; i++)
  148. {
  149. if (!InvalidIP.Contains($"{IPSegment}{i}") && !DeviceLists.ContainsKey($"{IPSegment}{i}"))
  150. {
  151. string pattern = @"^(([1-9]\d?)|(1\d{2})|(2[01]\d)|(22[0-3]))(\.((1?\d\d?)|(2[04]/d)|(25[0-5]))){3}$";
  152. if (Regex.IsMatch($"{IPSegment}{i}", pattern))
  153. {
  154. IPLists.Add($"{IPSegment}{i}");
  155. }
  156. }
  157. }
  158. IPLists.ForEach((item) =>
  159. {
  160. Ping myPing = new Ping();
  161. myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
  162. myPing.SendAsync(item, 1000, null);
  163. });
  164. }
  165. private void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
  166. {
  167. if (e.Reply.Status == IPStatus.Success)
  168. {
  169. string ip = e.Reply.Address.ToString();
  170. if (!DeviceLists.ContainsKey(ip))
  171. {
  172. DeviceStatus DS = new DeviceStatus();
  173. DS.modbusTcp.IsReconnect = false;
  174. DS.modbusTcp.ConnectOk = new Action(() =>
  175. {
  176. string DeviceName = DS.modbusTcp.GetString(DeviceAddress.DeviceName, 20).Trim()?.Replace(" ", "");//读取设备名称
  177. if (DeviceName.Length > 0)
  178. {
  179. DeviceLists.TryAdd(ip, DS);
  180. DeviceLists[ip].Init(DeviceName);
  181. DeviceLists[ip].modbusTcp.IsReconnect = false;
  182. App.Current.Dispatcher.Invoke(new Action(() =>
  183. {
  184. devices.Add(new Devices() { DeviceName = DeviceName, IpAddress = ip });
  185. if (TopDeviceCurrentStatuses.Count <= 7)
  186. TopDeviceCurrentStatuses.Add(new DeviceCurrentStatus() { DeviceName = DeviceName });
  187. else
  188. BottomDeviceCurrentStatuses.Add(new DeviceCurrentStatus() { DeviceName = DeviceName });
  189. for (int i = 0; i < Json<LocaPar>.Data.Recipes.Count; i++)
  190. {
  191. for (int m = 0; m < Json<LocaPar>.Data.Recipes.ElementAt(i).RawMaterials.Count; m++)
  192. {
  193. if (Json<LocaPar>.Data.Recipes.ElementAt(i).RawMaterials.ElementAt(m).DeviceIp == ip)
  194. {
  195. Json<LocaPar>.Data.Recipes.ElementAt(i).RawMaterials.ElementAt(m).RawMaterialName = DeviceName;
  196. }
  197. }
  198. }
  199. if (Global.DeviceRawMaterials.Count > 0)
  200. {
  201. if (Global.DeviceRawMaterials.FirstOrDefault(p => p.RawMaterialName == DeviceName) == null)
  202. {
  203. Global.DeviceRawMaterials.Add(new RawMaterialModel() { RawMaterialName = DeviceName, DeviceIp = ip, RawMaterialSource = 1 });
  204. }
  205. }
  206. else
  207. {
  208. Global.DeviceRawMaterials.Add(new RawMaterialModel() { RawMaterialName = DeviceName, DeviceIp = ip, RawMaterialSource = 1 });
  209. }
  210. }));
  211. }
  212. else
  213. {
  214. if (!InvalidIP.Contains(ip)) InvalidIP.Add(ip);
  215. }
  216. });
  217. DS.modbusTcp.ConnectFail = new Action(() =>
  218. {
  219. if (!InvalidIP.Contains(ip)) InvalidIP.Add(ip);
  220. });
  221. DS.modbusTcp.Disconnect = new Action(() =>
  222. {
  223. if (InvalidIP.Contains(ip)) InvalidIP.Remove(ip);
  224. var res = devices.FirstOrDefault(P => P.IpAddress == ip);
  225. if (res != null && devices.Contains(res))
  226. {
  227. App.Current.Dispatcher.Invoke(new Action(() =>
  228. {
  229. devices.Remove(res);
  230. var item = Global.DeviceRawMaterials.FirstOrDefault(P => P.RawMaterialName == res.DeviceName);
  231. if (item != null) Global.DeviceRawMaterials.Remove(item);
  232. var topRes = TopDeviceCurrentStatuses.FirstOrDefault(p => p.DeviceName == res.DeviceName);
  233. var bottomRes = BottomDeviceCurrentStatuses.FirstOrDefault(p => p.DeviceName == res.DeviceName);
  234. if (topRes != null) TopDeviceCurrentStatuses.Remove(topRes);
  235. if (bottomRes != null) BottomDeviceCurrentStatuses.Remove(bottomRes);
  236. }));
  237. }
  238. if (DeviceLists.ContainsKey(ip)) DeviceLists[ip].Dispose();
  239. });
  240. Task.Run(new Action(() =>
  241. {
  242. DS.modbusTcp.ModbusTcpConnect(ip, 502);//PLC连接
  243. IPQueues.Enqueue(e.Reply.Address.ToString());
  244. }));
  245. }
  246. else IPQueues.Enqueue(e.Reply.Address.ToString());
  247. }
  248. else IPQueues.Enqueue(e.Reply.Address.ToString());
  249. }
  250. }
  251. public class DeviceStatus
  252. {
  253. #region 对象属性声明
  254. public string DeviceName = String.Empty;
  255. public string IpAddress => modbusTcp.IPAdress;
  256. /// <summary>
  257. /// 设备状态
  258. /// </summary>
  259. public RawMaterialDeviceStatus deviceStatus { get; set; } = new RawMaterialDeviceStatus();
  260. public ModbusTcp modbusTcp = new ModbusTcp();
  261. public bool IsConnected => modbusTcp.Connected;
  262. #endregion
  263. public void Init(string DeviceName)
  264. {
  265. modbusTcp.Show = new Action<string>((s) => { MessageNotify.GetInstance.ShowRunLog(s); });
  266. modbusTcp.ShowEx = new Action<string>((s) => { MessageNotify.GetInstance.ShowRunLog(s); });
  267. this.DeviceName = DeviceName;
  268. AlarmHelper<AlarmInfo>.Init();
  269. if (modbusTcp.Connected)
  270. {
  271. ThreadManage.GetInstance().StartLong(new Action(() =>
  272. {
  273. this.DeviceName = modbusTcp.GetString(DeviceAddress.DeviceName, 20)?.Trim()?.Replace(" ", "");
  274. deviceStatus.RunStatus = (ushort)this.modbusTcp.ReadShort(DeviceAddress.RunStatus); //获取设备运行状态
  275. deviceStatus.WeightFeedback = (float)this.modbusTcp.GetUint(DeviceAddress.WeightFeedback);//获取设备料仓剩余重量
  276. deviceStatus.NowWeightFeedback = (float)this.modbusTcp.GetUint(DeviceAddress.CutWeightFeedback);//获取下料重量
  277. deviceStatus.DeviceNum = (ushort)this.modbusTcp.ReadShort(DeviceAddress.DeviceNum);//获取设备编号
  278. deviceStatus.DeviceAlarmCode = (ushort)this.modbusTcp.ReadShort(DeviceAddress.DeviceAlarmCode);//获取设备故障编码
  279. AlarmHelper<AlarmInfo>.GetInstance(DeviceName).EStop1 = deviceStatus.DeviceAlarmCode.GetBitValue(1);
  280. AlarmHelper<AlarmInfo>.GetInstance(DeviceName).Servo = deviceStatus.DeviceAlarmCode.GetBitValue(2);
  281. AlarmHelper<AlarmInfo>.GetInstance(DeviceName).Inverter = deviceStatus.DeviceAlarmCode.GetBitValue(3);
  282. AlarmHelper<AlarmInfo>.GetInstance(DeviceName).EStop2 = deviceStatus.DeviceAlarmCode.GetBitValue(7);
  283. AlarmHelper<AlarmInfo>.GetInstance(DeviceName).SiloUpperLimit = deviceStatus.DeviceAlarmCode.GetBitValue(8);
  284. AlarmHelper<AlarmInfo>.GetInstance(DeviceName).SiloLowerLimit = deviceStatus.DeviceAlarmCode.GetBitValue(9);
  285. Thread.Sleep(10);
  286. }), $"{DeviceName} 开始监听", true);
  287. }
  288. }
  289. public void SetDeviceName(string name)
  290. {
  291. this.modbusTcp.Write(DeviceAddress.DeviceName, new ushort[20]);
  292. this.modbusTcp.SetString(DeviceAddress.DeviceName, name);
  293. }
  294. public void StatusReset()
  295. {
  296. this.modbusTcp.Write(DeviceAddress.FinfishStatus, (ushort)1);
  297. //var res = modbusTcp.Read(DeviceAddress.RunStatus);
  298. }
  299. public void Dispose()
  300. {
  301. ThreadManage.GetInstance().StopTask($"{DeviceName} 开始监听");
  302. }
  303. public void Start(float Value)
  304. {
  305. if (modbusTcp.Connected)
  306. {
  307. modbusTcp.SetReal(DeviceAddress.WeightSet, Value);//写入配方量
  308. modbusTcp.Write(DeviceAddress.Start, (ushort)1);//设备启动写入
  309. MessageNotify.GetInstance.ShowRunLog($"{DeviceName},设置重量:{Value}");
  310. //配料设备参数写入
  311. var res = Json<DevicePar>.Data.deviceParModels.FirstOrDefault(p => p.MaterialName == DeviceName);
  312. if (res != null)
  313. {
  314. modbusTcp.SetReal(DeviceAddress.SlowlyAddWeight, res.SlowlyAddWeight);
  315. modbusTcp.SetReal(DeviceAddress.PreCloseValveWeight, res.PreCloseValveWeight);
  316. modbusTcp.SetUint(DeviceAddress.RapidAcceleration, (uint)res.RapidAcceleration);
  317. modbusTcp.SetUint(DeviceAddress.SlowAcceleration, (uint)res.SlowAcceleration);
  318. modbusTcp.SetUint(DeviceAddress.ServoManualSpeed, (uint)res.ServoManualSpeed);
  319. modbusTcp.SetUint(DeviceAddress.SiloUpperLimitWeight, (uint)res.SiloUpperLimitWeight);
  320. modbusTcp.SetUint(DeviceAddress.LowerLimitWeightOfSilo, (uint)res.LowerLimitWeightOfSilo);
  321. modbusTcp.SetUint(DeviceAddress.StirringSpeed, (uint)res.StirringSpeed);
  322. MessageNotify.GetInstance.ShowRunLog($"{res.MaterialName},参数下发完成");
  323. }
  324. }
  325. }
  326. }
  327. }