Exemplo n.º 1
0
		static void Init()
		{
			Console.WriteLine("Инициализация системы...");

			var connection = new ComPort
			{
				PortName = "COM2",
				BaudRate = 9600,
			};

			var network = new IncotexNetworkController
			{
				Connection = connection
			};

			_Device = new Mercury203
			{
				Address = 23801823
			};

			network.Devices.Add(_Device);

			NetworksManager.Instance.Networks.Add(network);

			_Device.Start();
			network.Start();
		}
Exemplo n.º 2
0
		void EventHandler_FormMain_Load(object sender, EventArgs e)
		{
			#region the code is For debug

			var connection = 
				new ResursNetwork.Incotex.NetworkControllers.DataLinkLayer.ComPort
			{
				PortName = "COM2",
				BaudRate = 9600,
			};

			var network = new IncotexNetworkController
			{
				Connection = connection
			};

			var device = new Mercury203
			{
				Address = 23801823
			};

			network.Devices.Add(device);

			_NetworksManager.Networks.Add(network);

			device.Start();
			network.Start();

			#endregion
			
			InitTreeViewSystem(_treeViewSystem);
			InitContextMenuSystem();
		}
        //[ExpectedException(typeof(InvalidOperationException), "")]
        public void TestWriteByWrongReqeustType()
        {
            // Arrange
            var msg = new DataMessage(new byte[] { 0, 0, 0, 2 })
            {
                Address = 1,
                CmdCode = 0x20,
                MessageType = MessageType.IncomingMessage
            };

            Mock<IDataLinkPort> comPort = new Mock<IDataLinkPort>();
            comPort.Setup(p => p.IsOpen).Returns(true);
            comPort.Setup(p => p.MessagesToRead).Returns(0);

            comPort.Setup(p => p.Write(It.IsAny<IMessage>()))
                .Raises(m => m.MessageReceived += null, new EventArgs());
            comPort.Setup(p => p.Read()).Returns(msg);

            var controller = new IncotexNetworkController();
            controller.Connection = comPort.Object;
            var device = new Mercury203();
            controller.Devices.Add(device);
            controller.Start();

            var request = new DataMessage()
            {
                Address = 0x1,
                CmdCode = Convert.ToByte(Mercury203CmdCode.ReadGroupAddress)
            };
            var wrongTrans = new Transaction(null, TransactionType.Undefined, request) { Sender = device }; // Ошибка !!!
            var networkRequest = new NetworkRequest(wrongTrans);

            // Act
            try
            {
                controller.Write(networkRequest);

                while (networkRequest.Status != NetworkRequestStatus.Failed)
                {
                    // Ждём, должно быть исключение
                }
            }
            catch (Exception ex)
            {
                // Assert
                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Создаёт сеть на основе типа и добавляет в коллекцию
        /// </summary>
        /// <param name="network">Объект сети из БД</param>
        public void AddNetwork(ResursAPI.Device network)
        {
            switch (network.DeviceType)
            {
                case ResursAPI.DeviceType.Network:
                    {
                        switch(network.DriverType)
                        {
                            case ResursAPI.DriverType.IncotextNetwork:
                                {
                                    var incotexPort = new Incotex.NetworkControllers.DataLinkLayer.ComPort
                                    {
                                        BaudRate = (int)network.GetParameter(
                                            ParameterNamesIncotexNetwork.BautRate),
                                        PortName = ((ParameterStringContainer)network.GetParameter(
                                            ParameterNamesIncotexNetwork.PortName)).GetValue()
                                    };

                                    var incotexController = new IncotexNetworkController
                                    {
                                        Id = (Guid)network.GetParameter(ParameterNamesIncotexNetwork.Id),
                                        Connection = (IDataLinkPort)incotexPort,
                                        BroadcastRequestDelay = (int)network.GetParameter(
                                            ParameterNamesIncotexNetwork.BroadcastDelay),
                                        RequestTimeout = (int)network.GetParameter(
                                            ParameterNamesIncotexNetwork.Timeout)
                                    };

                                    _NetworkControllers.Add((INetwrokController)incotexController);

                                    if (network.IsActive)
                                    { 
                                        incotexController.Start(); 
                                    }
                                    else
                                    {
                                        incotexController.Stop(); 
                                    }

                                    break; 
                                }
							case DriverType.VirtualIncotextNetwork:
								{
									var controller = new IncotexNetworkControllerVirtual
									{
										Id = (Guid)network.GetParameter(ParameterNamesIncotexNetworkVirtual.Id),
										PollingPeriod = (int)network.GetParameter(ParameterNamesIncotexNetworkVirtual.PollInterval)
									};

									_NetworkControllers.Add((INetwrokController)controller);

									if (network.IsActive)
									{
										controller.Start();
									}
									else
									{
										controller.Stop();
									}

									break; 

								}
                            default:
                                {
                                    throw new NotSupportedException(String.Format(
                                        "Устройтсво с DriverType={0} не поддерживается", 
                                        network.DriverType.ToString()));
                                }
                        }
                        break; 
                    }
                case ResursAPI.DeviceType.Counter:
                    { 
                        throw new InvalidCastException(
                            "Попытка приветсти счётчик эл энергии к контроллеру сети"); 
                    }
                default:
                    {
                        throw new InvalidCastException(String.Format(
                          "Неудалось привести типы. Устройтсво с DeviceType={0} не поддерживается",
                          network.DeviceType.ToString()));
                    }
            }
        }
        public void TestReadGroupAddressSuccess()
        {
            // Arrange
            int amount = 1;

            var msg = new DataMessage(new byte[] { 0, 0, 0, 2 })
            {
                Address = 1,
                CmdCode = 0x20,
                MessageType = MessageType.IncomingMessage
            };

            Mock<IDataLinkPort> comPort = new Mock<IDataLinkPort>();
            //comPort.Setup(p => p.GetType()).Returns(typeof(IncotexNetworkController));
            comPort.Setup(p => p.IsOpen).Returns(true);
            comPort.Setup(p => p.MessagesToRead)
                .Returns(() => amount)
                .Callback(() => amount--);

            comPort.Setup(p => p.Write(It.IsAny<IMessage>()))
                .Raises(m => m.MessageReceived += null, new EventArgs());
            comPort.Setup(p => p.Read()).Returns(msg);

            var controller = new IncotexNetworkController();
            controller.Connection = comPort.Object;
            controller.Start();
            //controller.Stop();

            var device = new Mercury203()
            {
                Address = 1,
            };

            controller.Devices.Add(device);

            // Act
            var result = device.ReadGroupAddress();
            //controller.Write(trans);
            do
            {
                // Ждём выполения комманды
            }
            while (!result.IsCompleted);

            // Assert
            Assert.AreEqual(TransactionStatus.Completed, result.Stack[result.Stack.Length - 1].Status, "Success");
        }
        //[ExpectedException(typeof(InvalidOperationException), "")]
        public void TestReadGroupAddressByControllerIsStopped()
        {
            // Arrange
            var msg = new DataMessage(new byte[] { 0, 0, 0, 2 })
            {
                Address = 1,
                CmdCode = 0x20,
                MessageType = MessageType.IncomingMessage
            };

            Mock<IDataLinkPort> comPort = new Mock<IDataLinkPort>();
            comPort.Setup(p => p.IsOpen).Returns(true);
            comPort.Setup(p => p.MessagesToRead).Returns(0);

            comPort.Setup(p => p.Write(It.IsAny<IMessage>()))
                .Raises(m => m.MessageReceived += null, new EventArgs());
            comPort.Setup(p => p.Read()).Returns(msg);

            var controller = new IncotexNetworkController();
            controller.Connection = comPort.Object;
            controller.Stop(); // Контроллер остановлен

            var device = new Mercury203()
            {
                Address = 1,
            };

            controller.Devices.Add(device);

            Type type = null;

            // Act
            try
            {
                var result = device.ReadGroupAddress();
            }
            catch (Exception ex)
            {
                type = ex.GetType();
            }

            // Assert
            Assert.AreEqual(typeof(InvalidOperationException), type);

            // Assert
            //while(true)
            //{
                // Ждём должно быть исключение
            //}
        }