123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- using MV485.model;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MV485.helper
- {
- public class PollingManager
- {
- private Dictionary<string, SerialPollingGroup> _groups = new Dictionary<string, SerialPollingGroup>();
- //增加了设备明细
- public event Action<TSlaveDetail> SlaveDetailAdded;
- //改变了设备状态
- public event Action<string, RunStatusType> SlaveStatusChanged;
- private bool _blPause;
- public PollingManager(bool blPause)
- {
- _blPause = blPause;
- }
- public void Pause()
- {
- _blPause = true;
- foreach (var kvp in _groups)
- {
- var group = kvp.Value;
- group.Pause();
- }
- }
- public void Resume()
- {
- _blPause = false;
- foreach(var group in _groups.Values)
- {
- group.Resume();
- }
- }
- //增加设备
- public void AddDevice(TSlave device)
- {
- if(!_groups.TryGetValue(device.PortName,out var group))
- {
- group = new SerialPollingGroup(device.PortName,_blPause);
- group.SlaveDetailAdded += Group_OnAddSlaveDetail;
- group.SlaveStatusChanged += Group_OnSlaveRunStatusChanged;
- _groups[device.PortName] = group;
- group.StartPolling();
- }
- group.AddDevice(device);
- }
- private void Group_OnSlaveRunStatusChanged(string slaveId, RunStatusType status)
- {
- SlaveStatusChanged?.Invoke(slaveId, status);
- }
- private void Group_OnAddSlaveDetail(TSlaveDetail detail)
- {
- SlaveDetailAdded?.Invoke(detail);
- }
- //批量增加
- public void AddDevice(ObservableCollection<TSlave> slaveList)
- {
- foreach(var slave in slaveList)
- {
- AddDevice(slave);
- }
- }
- public void RemoveDevice(string slaveId)
- {
- var emptyPorts = new List<string>();
- foreach (var kvp in _groups)
- {
- var port = kvp.Key;
- var group = kvp.Value;
- group.RemoveDevice(slaveId);
- if (!group.HasAnyDevice())
- {
- group.StopPolling();
- emptyPorts.Add(port);
- }
- }
- // 清理空的串口分组
- foreach (var port in emptyPorts)
- {
- _groups.Remove(port);
- }
- }
- public void RemoveAllDevice()
- {
- var emptyPorts = new List<string>();
- foreach (var group in _groups.Values)
- {
- group.StopPolling();
- group.RemoveAllDevice();
- //_groups.Remove(group.PortName);
- emptyPorts.Add(group.PortName);
- }
- foreach(var port in emptyPorts)
- {
- _groups.Remove(port);
- }
- //for(int i = _groups.Count; i >= 0; i++)
- //{
- // _groups.Remove(_groups.Keys[]);
- //}
- }
- public void StopAll()
- {
- foreach(var group in _groups.Values)
- {
- group.StopPolling();
- }
- }
- ////////////////////////////////////////////////////////////////
- }
- }
|