Ejemplo n.º 1
0
        public static void Tcp()
        {
            var slaveClient = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), 502);

            using (var slave = ModbusTcpSlave.CreateTcp((byte)1, slaveClient))
            {
                StartSlave(slave);

                IPAddress address      = new IPAddress(new byte[] { 127, 0, 0, 1 });
                var       masterClient = new TcpClient(address.ToString(), 502);

                using (var master = ModbusIpMaster.CreateIp(masterClient))
                    ReadRegisters(master);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Simple Modbus UDP master write coils example.
        /// </summary>
        public static void ModbusUdpMasterWriteCoils()
        {
            using (UdpClient client = new UdpClient())
            {
                IPEndPoint endPoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 502);
                client.Connect(endPoint);

                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                ushort startAddress = 1;

                // write three coils
                master.WriteMultipleCoils(startAddress, new bool[] { true, false, true });
            }
        }
Ejemplo n.º 3
0
        private static void mainThreadFunc()
        {
            while (true)
            {
                if (MainThread.exitEvent.WaitOne(1000))
                {
                    break;
                }

                #region 启动Dbus
                //启动监听进程
                if (SyncState.Dbus == false)
                {
                    dbusThread = new ExThread(Syncdbus);
                    dbusThread.Start();
                    MyConsole.Add("监听Dbus线程已启动!", Color.Green);
                    SyncState.Dbus = true;
                }
                #endregion

                #region 启动ModbusTcp
                if (SyncState.ModbusTcp == false)
                {
                    try
                    {
                        MyConsole.Add(string.Format("开始连接ModbusTcp客户端,IP地址:{0},Port:{1}", Profinet.ModbusTcpSeverIPAddress, Profinet.ModbusTcpSeverPort));
                        //连接超时1000ms
                        TcpClient tcpClient = new ExTcpClient(Profinet.ModbusTcpSeverIPAddress, Profinet.ModbusTcpSeverPort, 1000).Connect();
                        modbusMaster = ModbusIpMaster.CreateIp(tcpClient);
                        modbusMaster.Transport.WriteTimeout            = Profinet.Timeout;         //写超时
                        modbusMaster.Transport.ReadTimeout             = Profinet.Timeout;         //读超时
                        modbusMaster.Transport.WaitToRetryMilliseconds = Profinet.WaitToRetryTime; //重试等待时间
                        modbusMaster.Transport.Retries = Profinet.RetryNum;                        //重试次数

                        //启动监听进程
                        modbusThread = new ExThread(SyncModbus);
                        modbusThread.Start();
                        SyncState.ModbusTcp = true;
                        MyConsole.Add("监听ModbusTCP线程启动成功!", Color.Green);
                    }
                    catch
                    {
                        MyConsole.Add("监听ModbusTCP线程启动失败!", Color.Red);
                    }
                }
                #endregion
            }
        }
Ejemplo n.º 4
0
    public MeasureForm(int _devno, SerialPort _sp, TcpClient _tc, Sensor _ts)
    {
        InitializeComponent();
        SettingButton.Click  += SettingButton_Click;
        ExecButton.Click     += ExecButton_Click;
        UpdateButton.Click   += UpdateButton_Click;
        CoilsButton.Click    += CoilsButton_Click;
        DescriteButton.Click += DescriteButton_Click;
        UptimeButton.Click   += UptimeButton_Click;
        RawButton.Click      += RawButton_Click;
        CyclicPeriod.Minimum  = 100m;
        CyclicPeriod.Maximum  = 10000m;
        CyclicPeriod.Value    = 1000m;
        fs = null;
        sw = null;
        DataGridView dataGridView = dataGridView1;

        dataGridView.AutoSize              = true;
        dataGridView.Anchor                = (AnchorStyles.Top | AnchorStyles.Left);
        dataGridView.RowHeadersVisible     = false;
        dataGridView.AllowUserToAddRows    = false;
        dataGridView.MultiSelect           = false;
        dataGridView.SelectionMode         = DataGridViewSelectionMode.CellSelect;
        dataGridView.ColumnCount           = 2;
        dataGridView.Columns[0].HeaderText = "Item";
        dataGridView.Columns[0].SortMode   = DataGridViewColumnSortMode.NotSortable;
        dataGridView.Columns[1].HeaderText = "Value";
        dataGridView.Columns[1].SortMode   = DataGridViewColumnSortMode.NotSortable;
        TargetSensor = _ts;
        TargetSensor.SensorComponent(dataGridView);
        devno = _devno;
        if (_sp != null)
        {
            Tc = null;
            Sp = _sp;
            Sp.Open();
            Master = ModbusSerialMaster.CreateRtu(_sp);
        }
        else
        {
            Sp     = null;
            Tc     = _tc;
            Master = ModbusIpMaster.CreateIp(Tc);
        }
        Master.Transport.ReadTimeout       = 300;
        dataGridView.CurrentCell           = dataGridView[1, 0];
        dataGridView.AllowUserToResizeRows = false;
    }
Ejemplo n.º 5
0
        public static void Write_MultipleCoils(ushort write_start_addr, bool[] coils_value)
        {
            coils_value      = _writemultiplecoils_Value;
            write_start_addr = _writestartAddress;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            master.WriteMultipleCoils(write_start_addr, coils_value);

            Stop_MBClient();
            Stop_MBServer();
        }
Ejemplo n.º 6
0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public static void Write_SingleCoil(ushort write_coil_addr, bool coil_value)
        {
            write_coil_addr = _writecoil_Address;
            coil_value      = _writecoil_Value;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            master.WriteSingleCoil(_writecoil_Address, _writecoil_Value);

            Stop_MBClient();
            Stop_MBServer();
        }
Ejemplo n.º 7
0
        public static void Write_MultipleRegisters(ushort write_register_addr, ushort[] register_data)
        {
            write_register_addr = _register_Address;
            register_data       = _register_Data;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            master.WriteMultipleRegisters(write_register_addr, register_data);

            Stop_MBClient();
            Stop_MBServer();
        }
Ejemplo n.º 8
0
        public static void Udp()
        {
            var slaveClient = new UdpClient(502);

            using (var slave = ModbusUdpSlave.CreateUdp(slaveClient))
            {
                StartSlave(slave);

                var        masterClient = new UdpClient();
                IPEndPoint endPoint     = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 502);
                masterClient.Connect(endPoint);

                using (var master = ModbusIpMaster.CreateIp(masterClient))
                    ReadRegisters(master);
            }
        }
Ejemplo n.º 9
0
        public static void Write_SingleRegister(ushort write_register_addr, ushort register_value)
        {
            write_register_addr = _register_Address;
            register_value      = _register_Value;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            master.WriteSingleRegister(write_register_addr, register_value);

            Stop_MBClient();
            Stop_MBServer();
        }
Ejemplo n.º 10
0
        private static void ReadAndDisplay()
        {
            if (CheckConnection(IpAddress, 100))
            {
                ushort[] regData;
                bool[]   coilData;
                while (true)
                {
                    using (TcpClient client = new TcpClient(IpAddress, 502)) {
                        ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                        regData  = master.ReadHoldingRegisters(0, 16);
                        coilData = master.ReadCoils(0, 48);
                        client.Close();
                        master.Dispose();
                    }
                    Console.WriteLine("Analog");
                    for (int i = 0; i < regData.Length; i++)
                    {
                        //double x = regData[i];
                        //x = (x / 1000);
                        //double y = SlopeValues[i] * x + OffsetValues[i];
                        //double current = (RValues[i] != 0) ? (y / RValues[i]) * 1000 : 0.00;

                        Console.WriteLine(" A{0}: Voltage: {1} Current: {2}", i, regData[i]);
                    }
                    Console.WriteLine();
                    Console.WriteLine("Digitals Pull-up: ");
                    for (int i = 0; i < 22; i++)
                    {
                        Console.WriteLine(" D{0}: {1}", i, coilData[i]);
                    }

                    Console.WriteLine();
                    Console.WriteLine("Press C to continue");
                    var key = Console.ReadKey();
                    if (key.Key != ConsoleKey.C)
                    {
                        break;
                    }
                }
            }
            else
            {
                Console.WriteLine("Connection Failed");
            }
            Console.ReadKey();
        }
Ejemplo n.º 11
0
        private Task <bool> ConnectTask()
        {
            return(Task.Run(() =>
            {
                if (master != null)
                {
                    master.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                }
                if (CheckInternet())
                {
                    try
                    {
                        client = new TcpClient();
                        IAsyncResult asyncResult = client.BeginConnect(cGenel.conDXM_IP, 502, null, null);
                        asyncResult.AsyncWaitHandle.WaitOne(1000, true); //wait for 3 sec
                        if (!asyncResult.IsCompleted)
                        {
                            client.Close();
                            cGenel.haberlesmeMesaj = (DateTime.Now.ToString() + ":DXM Cannot connect to server.(task)");
                            error_kayit.error_log_kayit(cGenel.haberlesmeMesaj);
                            return false;
                        }
                        // create Modbus TCP Master by the tcpclient
                        master = ModbusIpMaster.CreateIp(client);
                        master.Transport.Retries = 3; //don't have to do retries
                        master.Transport.ReadTimeout = 1500;
                        master.Transport.WaitToRetryMilliseconds = 50;

                        cGenel.haberlesmeMesaj = (DateTime.Now.ToString() + ":DXM Connect to server.(task)");
                        error_kayit.error_log_kayit(cGenel.haberlesmeMesaj);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        cGenel.haberlesmeMesaj = (DateTime.Now.ToString() + ":DXM Connect process (task) " + ex.StackTrace +
                                                  "==>" + ex.Message);
                        error_kayit.error_log_kayit(cGenel.haberlesmeMesaj);
                        return false;
                    }
                }
                return false;
            }));
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Input IP address of modbus slave");
            var ip = Console.ReadLine();

            Console.WriteLine("Input port");
            int  port;
            var  t = int.TryParse(Console.ReadLine(), out port);
            byte slaveId;

            Console.WriteLine("Input slaveId");
            t = byte.TryParse(Console.ReadLine(), out slaveId);
            while (true)
            {
                try
                {
                    using (TcpClient client = new TcpClient(ip, port))
                    {
                        ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                        // read five input values
                        ushort startAddress = 0;
                        ushort numHoldings  = 10;
                        while (true)
                        {
                            ushort[] inputs = master.ReadHoldingRegisters(slaveId, startAddress, numHoldings);
                            //bool[] inputs = master.ReadCoils(slaveId, startAddress, numHoldings);
                            Console.Write(startAddress + "::");
                            for (int i = 0; i < inputs.Length; i++)
                            {
                                Console.Write(" " + (inputs[i]));
                            }
                            Console.WriteLine();
                            startAddress += 10;
                            Thread.Sleep(500);
                        }
                        Console.Read();
                    }
                }
                catch (Exception ex)
                {
                    var tmp = (SlaveException)ex;
                    Console.WriteLine(tmp.Message + tmp.SlaveExceptionCode);
                    Console.Read();
                }
            }
        }
Ejemplo n.º 13
0
        private async Task GetDataFromBlockAsync()
        {
            using (var tcpClient = new TcpClient())
            {
                tcpClient.Connect(_remoteEP);

                int len = _sensorInstance.SampleMaps.Sum(i => i.Len);

                using (var modbusMaster = ModbusIpMaster.CreateIp(tcpClient))
                {
                    //modbusMaster.Transport.ReadTimeout = 300;
                    while (_isRunning)
                    {
                        int           idx     = 0;
                        byte[]        frame   = Utils.FrameToByte(await modbusMaster.ReadInputRegistersAsync((byte)0, (ushort)_sensorInstance.SamplingAddress, (ushort)(len / 2)));
                        List <string> lstData = new List <string>();

                        foreach (typeBase sampleMap in _sensorInstance.SampleMaps)
                        {
                            if (!sampleMap.Title.ToUpper().StartsWith("CH"))
                            {
                                continue;
                            }

                            sampleMap.FrameTo(frame, idx);
                            idx += sampleMap.Len;

                            lstData.Add(sampleMap.ToString());
                        }

                        if (HandleWhenReceiveDataFromBlock != null)
                        {
                            HandleWhenReceiveDataFromBlock(this, lstData.ToArray());
                        }

                        Thread.Sleep(95);
                    }

                    if (HandleWhenReceiveDataEndFromBlock != null)
                    {
                        HandleWhenReceiveDataEndFromBlock(this, new EventArgs());
                    }
                }
            }

            _threadReceiveDataFromBlock = null;
        }
    private static void Read(object state)
    {
        TcpClient?masterClient = new(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port);

        using ModbusIpMaster? master = ModbusIpMaster.CreateIp(masterClient);
        master.Transport.Retries     = 0;

        Random?random = new();

        for (int i = 0; i < 5; i++)
        {
            bool[] coils = master.ReadCoils(1, 1);
            Assert.Equal(1, coils.Length);
            Debug.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: Reading coil value");
            Thread.Sleep(random.Next(100));
        }
    }
Ejemplo n.º 15
0
        public GSBase(TcpClient MotTcp, TcpClient DetTcp, MainView main)
        {
            if (null == MotTcp)
            {
                throw new Exception("电机未连接");
            }
            Mot = ModbusIpMaster.CreateIp(MotTcp);

            if (null == DetTcp)
            {
                throw new Exception("探测器未连接");
            }
            Det = ModbusIpMaster.CreateIp(DetTcp);

            pMain   = main;
            listDet = new List <DetPara>();
        }
Ejemplo n.º 16
0
        // This method establishs a connection to the device. Therefore an IP address and the port number
        // for the TcpClient is need. The client itself is used for the implementation of the ModbusIpMaster.
        public void Connect()
        {
            try
            {
                _client    = new TcpClient(_iPAddress, _port);
                _master    = ModbusIpMaster.CreateIp(_client);
                _connected = true;

                BusActivityDetection?.Invoke(this, new LogEvent("Connection has been established successfully"));
            }
            catch (Exception)
            {
                _connected = false; // If the connection establishment has not been successful - connected=false.

                BusActivityDetection?.Invoke(this, new LogEvent("Connection has NOT been established successfully"));
            }
        }
Ejemplo n.º 17
0
        private static void ReadOnOwnThread(object state)
        {
            using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);
                master.Transport.Retries = 0;

                var random = new Random();
                for (int i = 0; i < 5; i++)
                {
                    bool[] coils = master.ReadCoils(1, 1);
                    Assert.AreEqual(1, coils.Length);
                    Debug.WriteLine(String.Format("{0}: Reading coil value", Thread.CurrentThread.ManagedThreadId));
                    Thread.Sleep(random.Next(100));
                }
            }
        }
Ejemplo n.º 18
0
 public static void Setpoint(ushort _setpoint)
 {
     try
     {
         TcpClient      tcpClient = new TcpClient(Properties.Settings.Default.VRF_Ip, Properties.Settings.Default.VRF_Port);
         ModbusIpMaster ipMaster  = ModbusIpMaster.CreateIp(tcpClient);
         byte           address   = Properties.Settings.Default.slaveAddress;
         ushort         addr      = 3;
         ipMaster.WriteSingleRegister(address, addr, _setpoint);
         Thread.Sleep(2000);
         setpoint = _setpoint;
         ipMaster.Dispose();
         tcpClient.GetStream().Close();
         tcpClient.Close();
     }
     catch { }
 }
Ejemplo n.º 19
0
        public static bool[] Read_Coils(ushort read_start_addr, ushort num_coils)
        {
            num_coils       = _numOfCoils;
            read_start_addr = _readstartAddress;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            bool[] read_result = master.ReadCoils(read_start_addr, num_coils);

            Stop_MBClient();
            Stop_MBServer();
            return(read_result);
        }
Ejemplo n.º 20
0
        public static ushort[] Read_InputRegisters(ushort read_start_addr, ushort num_register)
        {
            num_register    = _numOfInputRegister;
            read_start_addr = _readstartAddress;
            Start_MBServer();
            Start_MBCLient();
            ModbusSlave slave    = ModbusTcpSlave.CreateTcp(_slaveID, slaveTCP);
            var         listener = slave.ListenAsync();

            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTCP);

            ushort[] read_result = master.ReadInputRegisters(read_start_addr, num_register);

            Stop_MBClient();
            Stop_MBServer();
            return(read_result);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Simple Modbus TCP master write holding registers example.
        /// </summary>
        public async void ModbusTcpWriteSingleRegister()
        {
            ushort inputValue = ushort.Parse(InputTextBox.Text);

            using (TcpClient client = new TcpClient())
            {
                client.ReceiveTimeout = 3000;
                client.SendTimeout    = 3000;
                await client.ConnectAsync(IpAddressInputBox.Text, int.Parse(TcpPortInputBox.Text));

                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                ushort address = ushort.Parse(writeRegisterInputBox.Text);

                master.WriteSingleRegister(address, inputValue);
            }
        }
Ejemplo n.º 22
0
    public void OverrideTimeoutOnNetworkStream()
    {
        TcpListener?listener = new(ModbusMasterFixture.TcpHost, ModbusMasterFixture.Port);

        using ModbusTcpSlave? slave = ModbusTcpSlave.CreateTcp(ModbusMasterFixture.SlaveAddress, listener);
        Thread?slaveThread = new(async() => await slave.ListenAsync());

        slaveThread.Start();

        TcpClient?client = new(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port);

        client.GetStream().ReadTimeout  = 1500;
        client.GetStream().WriteTimeout = 3000;
        using ModbusIpMaster? master = ModbusIpMaster.CreateIp(client);
        Assert.Equal(1500, client.GetStream().ReadTimeout);
        Assert.Equal(3000, client.GetStream().WriteTimeout);
    }
Ejemplo n.º 23
0
        /// <summary>
        /// Modbus TCP master and slave Configuration for OmniID application.
        /// </summary>
        public static void ModbusTcpMasterSlaveConfigOmniID(IPAddress ModBusSlaveIP, byte SlaveId, int Port)
        {
            byte slaveId = SlaveId; //1
            int  port    = Port;    // 502;

            // create and start the TCP slave
            TcpListener slaveTcpListener = new TcpListener(ModBusSlaveIP, port);

            slaveTcpListener.Start();
            ModbusSlave slave       = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);
            Thread      slaveThread = new Thread(slave.Listen);

            slaveThread.Start();

            // create the master
            TcpClient      masterTcpClient = new TcpClient(ModBusSlaveIP.ToString(), port);
            ModbusIpMaster OmniMaster      = ModbusIpMaster.CreateIp(masterTcpClient);

            ushort numFlagInputs       = 1;
            ushort pollingAddressStart = 4000;
            ushort dataAddressStart    = 4001;
            int    numInputsTagID      = 5;
            int    numInputsWeight     = 5;
            ushort numInputs           = (ushort)(numInputsTagID + numInputsWeight);

            Thread pollingThreadOmni = new Thread(() => PollSlaveOmniId(OmniMaster, pollingAddressStart, numFlagInputs, dataAddressStart, numInputs));

            pollingThreadOmni.Start();


            Console.ReadKey();
            // clean up

            _shouldpoll = false;
            pollingThreadOmni.Join();
            masterTcpClient.Close();
            slaveTcpListener.Stop();

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Ejemplo n.º 24
0
 private void Analysis()
 {
     while (myWorkState)
     {
         TimeSpan timeSpan = DateTime.Now.Subtract(ReadTime);
         if (timeSpan.TotalSeconds >= 1)
         {
             try
             {
                 using (TcpClient tcp = new TcpClient(GateWaySetting.Gateways[0].Location, GateWaySetting.Gateways[0].Rate))
                 {
                     ModbusMaster ModbusMaster = ModbusIpMaster.CreateIp(tcp);
                     ModbusMaster.Transport.Retries      = 3;
                     ModbusMaster.Transport.ReadTimeout  = 1000;
                     ModbusMaster.Transport.WriteTimeout = 1000;
                     foreach (var item in AbsProtocols)
                     {
                         item.ReadData(GateWaySetting.Gateways[0].Devices, ModbusMaster);
                         Thread.Sleep(10);
                     }
                     if (AbsProtocols[0].ConnectionFlag)
                     {
                         AI64Module = ((AiProtocol)AbsProtocols[0]).AI64Module;
                     }
                     else
                     {
                         AI64Module = null;
                     }
                     StateModules = ((StateProtocol)AbsProtocols[1]).StateModules;
                     ReadTime     = DateTime.Now;
                 }
             }
             catch (ThreadAbortException) { }
             catch (Exception ex)
             {
                 ReadTime = DateTime.Now;
                 Log.Error(ex, $"通訊失敗 IP:{GateWaySetting.Gateways[0].Location} Port:{GateWaySetting.Gateways[0].Rate} ");
             }
         }
         else
         {
             Thread.Sleep(80);
         }
     }
 }
Ejemplo n.º 25
0
        public static void ModbusTcpMasterReadInputRegisters()
        {
            //byte slaveId = 1;
            int       port    = 502;
            IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });

            // create and start the TCP slave
            //TcpListener slaveTcpListener = new TcpListener(address, port);
            //slaveTcpListener.Start();
            //ModbusSlave slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);
            //Thread slaveThread = new Thread(slave.Listen);
            //slaveThread.Start();

            // create the master
            TcpClient      masterTcpClient = new TcpClient(address.ToString(), port);
            ModbusIpMaster master          = ModbusIpMaster.CreateIp(masterTcpClient);

            ushort numInputs    = 10;
            ushort startAddress = 0;

            // read five register values


            while (true)
            {
                ushort[] inputs = master.ReadInputRegisters(startAddress, numInputs);
                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Register {(startAddress + i)}={(inputs[i])}");
                }
                Thread.Sleep(1000);
            }


            // clean up
            //masterTcpClient.Close();
            //slaveTcpListener.Stop();

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Ejemplo n.º 26
0
        ThreePhaseMeasure IThreePhaseInputService.Get()
        {
            using (var client = new TcpClient(hostname, port))
                using (var master = ModbusIpMaster.CreateIp(client))
                {
                    ushort[] inputs = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

                    var measure = new ThreePhaseMeasure
                    {
                        Frequency = Converter.ConvertToFloat(inputs, 56),
                        L1        = GetPhase(inputs, 1),
                        L2        = GetPhase(inputs, 2),
                        L3        = GetPhase(inputs, 3),
                    };

                    return(measure);
                }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Wrire registers using Modbus TCP.
        /// </summary>
        /// <param name="slaveAddress">Slave device address.</param>
        /// <param name="startAddress">Start address for writing.</param>
        /// <param name="registers">Values of registers.</param>
        public static void WriteRegisters(byte slaveAddress, ushort startAddress, params ushort[] registers)
        {
            if (_client.Connected)
            {
                try
                {
                    var master = ModbusIpMaster.CreateIp(_client);

                    master.Transport.WriteTimeout = WriteTimeout;
                    master.Transport.Retries      = AttemptsModbus;
                    master.WriteMultipleRegisters(slaveAddress, startAddress, registers);
                }
                catch
                {
                    ++WriteErrors;
                }
            }
        }
Ejemplo n.º 28
0
        public ReadThread(string hostname, int port)
        {
            NReg      = (ushort)Sett.Instance.rdCoilSize;
            coilCount = RB.R.Length / NReg + 1;
            for (int i = 0; i < 2; i++)
            {
                tcp[i]       = new TcpClient(hostname, port);
                mbMasterR[i] = ModbusIpMaster.CreateIp(tcp[i]);

                /*
                 * if (i==0)
                 * thread[i] = new Thread(new ThreadStart(ThreadJob1));
                 * else
                 *  thread[i] = new Thread(new ThreadStart(ThreadJob2));
                 */
                //  thread[i].Start();
            }
        }
Ejemplo n.º 29
0
 public static void TurnOFF()
 {
     try
     {
         TcpClient      tcpClient = new TcpClient(Properties.Settings.Default.VRF_Ip, Properties.Settings.Default.VRF_Port);
         ModbusIpMaster ipMaster  = ModbusIpMaster.CreateIp(tcpClient);
         byte           address   = Properties.Settings.Default.slaveAddress;
         ushort         addr      = 0;
         ushort         val       = 0;
         ipMaster.WriteSingleRegister(address, addr, val);
         Thread.Sleep(2000);
         status = "OFF";
         ipMaster.Dispose();
         tcpClient.GetStream().Close();
         tcpClient.Close();
     }
     catch { }
 }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            using (TcpClient client = new TcpClient("192.168.5.178", 502))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                // read five input values
                ushort startAddress = 3200;
                ushort numInputs    = 25;
                //bool[] inputs = master.ReadInputs(startAddress, numInputs);
                ushort[] outHolding = master.ReadHoldingRegisters(startAddress, numInputs);

                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Input {(startAddress + i)}={"NULL"}");
                }
            }
        }