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

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