终端一体化运控平台
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.
 
 
 

366 lines
16 KiB

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