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

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