/// <summary> /// Конструктор /// </summary> /// <param name="networkName">Наименование данной сети</param> /// <param name="connection">Объект для физического подключения к сети</param> public NetworkController(String networkName, IDataLinkLayer connection) { NetworksManager manager = NetworksManager.Instance; // Проверяем уникальность наименование сети if (manager.Networks.Contains(networkName)) { throw new Exception( "Попытка создать сеть Modbus с наименованием, которое имеет другая сеть"); } else { _NetworkName = networkName; } _Devices = new DevicesCollection(this); _Devices.ItemsListWasChanged += new EventHandler(EventHandler_DevicesCollection_ItemsListWasChanged); _Connection = connection; if (_Connection != null) { _Connection.RequestWasRecived += new EventHandlerRequestWasRecived(EventHandler_Connection_RequestWasRecived); _Connection.ErrorOccurred += new EventHandlerErrorOccurred(EventHandler_Connection_ErrorAccured); // Переводим контроллер в состояние "стоп" Stop(); } }
//--------------------------------------------------------------------------- private void EventHandler_ComboBoxTypeConnection_SelectedIndexChanged( object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; InterfaceType type = (InterfaceType)Enum.Parse(typeof(InterfaceType), cb.SelectedItem.ToString()); this.Connection = CreateConnection(type, (TransmissionMode)Enum.Parse(typeof(TransmissionMode), comboBoxMode.SelectedItem.ToString())); return; }
/// <summary> /// Конструктор /// </summary> /// <param name="networkName">Наименование данной сети</param> /// <param name="connection">Объект для физического подключения к сети</param> public NetworkController(String networkName, IDataLinkLayer connection) { NetworksManager manager = NetworksManager.Instance; // Проверяем уникальность наименование сети if (manager.Networks.Contains(networkName)) { throw new Exception( "Попытка создать сеть Modbus с наименованием, которое имеет другая сеть"); } else { _NetworkName = networkName; } _Devices = new DevicesCollection(this); _Devices.ItemsListWasChanged += new EventHandler(EventHandler_DevicesCollection_ItemsListWasChanged); _Connection = connection; if (_Connection != null) { _Connection.RequestWasRecived += new EventHandlerRequestWasRecived(EventHandler_Connection_RequestWasRecived); _Connection.ErrorOccurred += new EventHandlerErrorOccurred(EventHandler_Connection_ErrorAccured); // Переводим контроллер в состояние "стоп" Stop(); } }
//--------------------------------------------------------------------------- private void EventHandler_ComboBoxTypeConnection_SelectedIndexChanged( object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; InterfaceType type = (InterfaceType)Enum.Parse(typeof(InterfaceType), cb.SelectedItem.ToString()); this.Connection = CreateConnection(type, (TransmissionMode)Enum.Parse(typeof(TransmissionMode), comboBoxMode.SelectedItem.ToString())); return; }
//--------------------------------------------------------------------------- /// <summary> /// Конструктор для десериализатора /// </summary> /// <param name="info"></param> /// <param name="context"></param> public DeviceOld(SerializationInfo info, StreamingContext context) { this._replyToRequest = new ProcessTheRequest(this.RequestParse); this._onReplyTransmitted = new EventOnReplyTransmitted(this.OnReplyTransmitted); this._onError = new EventOnError(this.OnError); this._onRequstRecived = new EventOnRequstRecived(this.OnRequestRecived); this.Address = info.GetByte("Address"); this._dataMap = (DataSet)info.GetValue("DataMap", typeof(DataSet)); Object[] settings = (Object[])info.GetValue("ConnectionSettings", typeof(Object)); switch ((InterfaceType)info.GetValue("ConnectionType", typeof(InterfaceType))) { case InterfaceType.SerialPort: { if ((TransmissionMode)info.GetValue("Mode", typeof(TransmissionMode)) == TransmissionMode.RTU) { // Режим передачи RTU ComPort comport = new ComPort(this.Address, (String)settings[0], (int)settings[1], (System.IO.Ports.Parity)settings[3], (int)settings[2], (System.IO.Ports.StopBits)settings[4]); _connection = (IDataLinkLayer)comport; } else { // Режим передачи ASCII throw new NotImplementedException(); } break; } case InterfaceType.TCPIP: { throw new NotImplementedException(); } default: { throw new NotImplementedException(); } } if (_connection != null) { _connection.ErrorAccured += new EventHandlerErrorAccured(EventHandler_DataLinkObject_ErrorOccured); _connection.ReplyWasTransmitted += new EventHandleReplyTransmitted(EventHandler_DataLinkObject_ReplyTransmited); _connection.RequestRecived += new EventHandlerRequestRecived(EventHandler_DataLinkObject_RequestRecived); } }
//--------------------------------------------------------------------------- /// <summary> /// Конструктор /// </summary> /// <param name="address">Сетевой адрес устройства</param> /// <param name="connection">Объект физического порта подключения</param> public DeviceOld(Byte address, IDataLinkLayer connection) { this.Address = address; this._replyToRequest = new ProcessTheRequest(this.RequestParse); this._onReplyTransmitted = new EventOnReplyTransmitted(this.OnReplyTransmitted); this._onError = new EventOnError(this.OnError); this._onRequstRecived = new EventOnRequstRecived(this.OnRequestRecived); this.InitDataMap(); this._connection = connection; if (_connection != null) { _connection.ErrorAccured += new EventHandlerErrorAccured(EventHandler_DataLinkObject_ErrorOccured); _connection.ReplyWasTransmitted += new EventHandleReplyTransmitted(EventHandler_DataLinkObject_ReplyTransmited); _connection.RequestRecived += new EventHandlerRequestRecived(EventHandler_DataLinkObject_RequestRecived); } }
//--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Constructors and Destructor //--------------------------------------------------------------------------- /// <summary> /// Конструктор /// </summary> private DeviceOld() { this.Address = 1; this.InitDataMap(); this._connection = null; }
public bool Start(string portName) { txQueue = new ConcurrentQueue <byte[]>(); md = new MessageDispatcher(); md.AddHandler <PingReplyMessage>(m => { devicePresence[m.Source - 1] = true; Console.WriteLine("Device {0} is present [{1:0.0} ms]", m.Source, (DateTime.Now - pingTimer).TotalMilliseconds); }); md.AddHandler <NothingTokenMessage>(m => { TokenReceived(m.Destination); }); md.AddHandler <ReportTokenMessage>(m => { TokenReceived(m.Destination); for (int i = 0; i < tokenRingLength - 1; i++) { qualityMatrix[m.Source - 1, i] = ((sbyte)m.Rssis[i]); } if (m.Destination == tokenRingLength) // last device in the ring means a full sweep has been made { Task.Factory.StartNew(() => { var now = DateTime.Now; var time = now - lastTime; lastTime = now; foreach (var lqi in lqis) // calculate lqi as the average of sensed RSSI by either end point of a link { int a = lqi.EndPointA; int b = lqi.EndPointB; if (qualityMatrix[a, b] > -5 || qualityMatrix[b, a] > -5) { lqi.Quality = 0; } else { lqi.Quality = (qualityMatrix[a, b] + qualityMatrix[b, a]) / 2.0; } } if (SweepCompleted != null) { SweepCompleted(lqis); } }); } }); try { var sp = new SerialPort(portName, 500000); var pl = new SerialPortWrapper(sp); dll = new FrameTransceiver(pl); dll.FrameReceived += md.HandleFrame; dll.Start(); } catch { return(false); } Thread.Sleep(200); DetectDevices(); // detect which devices are online and detect the length of the ring List <LinkQualityIndicator> l = new List <LinkQualityIndicator>(); qualityMatrix = new double[tokenRingLength - 1, tokenRingLength - 1]; for (int i = 0; i < tokenRingLength - 1; i++) { for (int j = 0; j < tokenRingLength - 1; j++) { qualityMatrix[i, j] = 0.0; if (i < j) { l.Add(new LinkQualityIndicator { EndPointA = i, EndPointB = j, Quality = 0.0 }); } } } lqis = l.ToArray(); Console.WriteLine("Found " + (tokenRingLength - 1) + " devices"); dll.Send(nothingToken); // start the token passing Console.WriteLine("Started"); return(true); }