コード例 #1
0
 public Tuple <ushort[], bool[]> ReadRegistersAndCoils(int regAddress, int regLength, int coilAddr, int coilLength)
 {
     ushort[] regData;
     bool[]   coilData;
     if (this.CheckConnection())
     {
         try {
             using TcpClient client = new TcpClient(this.IpAddress, this.Port);
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             if (this.SlaveAddress != 0)
             {
                 regData  = master.ReadHoldingRegisters(this.SlaveAddress, (ushort)regAddress, (ushort)regLength);
                 coilData = master.ReadCoils(this.SlaveAddress, (ushort)coilAddr, (ushort)coilLength);
             }
             else
             {
                 regData  = master.ReadHoldingRegisters((ushort)regAddress, (ushort)regLength);
                 coilData = master.ReadCoils((ushort)coilAddr, (ushort)coilLength);
             }
             client.Close();
             master.Dispose();
             return(new Tuple <ushort[], bool[]>(regData, coilData));
         } catch {
             return(null);
         }
     }
     return(null);
 }
コード例 #2
0
 public ushort[] ReadRegisters(int address, int length)
 {
     ushort[] regData;
     if (this.CheckConnection())
     {
         try {
             using TcpClient client = new TcpClient(this.IpAddress, this.Port);
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             if (this.SlaveAddress != 0)
             {
                 regData = master.ReadHoldingRegisters(this.SlaveAddress, (ushort)address, (ushort)length);
             }
             else
             {
                 regData = master.ReadHoldingRegisters((ushort)address, (ushort)length);
             }
             client.Close();
             master.Dispose();
             return(regData);
         } catch {
             return(null);
         }
     }
     return(null);
 }
コード例 #3
0
        private string GetDataArrayFromRegion(ERegionType eType,
                                              List <List <ushort> > listlistRegion,
                                              ref ushort[] regionData)
        {
            List <short[]> listData = new List <short[]>();

            foreach (var listT in listlistRegion)
            {
                for (int j = 0; j < listT.Count; j = j + 100)
                {
                    ushort num;
                    if ((listT.Count - j) > 100)
                    {
                        num = 100;
                    }
                    else
                    {
                        num = (ushort)(listT.Count - j);
                    }
                    ushort[] regs;
                    try
                    {
                        switch (eType)
                        {
                        case ERegionType.Region_AO:
                        {
                            Thread.Sleep(10);
                            regs = master.ReadHoldingRegisters(
                                (ushort)(CT2.ECT2HoldReg.RegionAO + listT[j] * 1),
                                (ushort)num);
                            regs.CopyTo(regionData, listT[j]);
                            break;
                        }

                        case ERegionType.Region_AI:
                        {
                            Thread.Sleep(10);
                            regs = master.ReadInputRegisters(
                                (ushort)(CT2.ECT2InputReg.RegionAI + listT[j] * 1),
                                (ushort)num);
                            regs.CopyTo(regionData, listT[j]);
                            break;
                        }

                        case ERegionType.Region_DI:
                        case ERegionType.Region_DO:
                        default:
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        return(e.Message);
                    }
                }
            }
            return("NO_ERR");
        }
コード例 #4
0
        /// <summary>
        /// this gets the position stored in the MCU which is based of the number of steps the MCU has taken since it was last 0ed out
        /// </summary>
        /// <returns></returns>
        public override Orientation read_Position()
        {
            ushort[] data = MCUModbusMaster.ReadHoldingRegisters(2, 12);
            // Console.WriteLine("AZ_finni2 {0,10} EL_finni2 {1,10}", (65536 * data[0]) + data[1], (65536 * data[10]) + data[11]);
            Orientation current_orientation = new Orientation(
                ConversionHelper.StepsToDegrees((data[0] << 16) + data[1], MotorConstants.GEARING_RATIO_AZIMUTH),
                ConversionHelper.StepsToDegrees((data[10] << 16) + data[11], MotorConstants.GEARING_RATIO_ELEVATION)
                );

            return(current_orientation);
        }
コード例 #5
0
ファイル: MainWindow.xaml.cs プロジェクト: SergDfv/UPanel
 private void ReadHoldReg(object sender, EventArgs e)
 {
     try
     {
         HoldingRegisters = master.ReadHoldingRegisters(20002, 36);
         Refresh_DI_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20038, 12);
         Refresh_Y_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20050, 58);
         Refresh_DO_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20108, 20);
         Refresh_U_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20148, 20);
         Refresh_mini_U_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20136, 12);
         Refresh_mini_DO_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20168, 20);
         Refresh_cpCOe_U_Labels();
         HoldingRegisters = master.ReadHoldingRegisters(20188, 12);
         Refresh_cpCOe_DO_Labels();
     }
     catch (Exception er)
     {
         Dispose_Connect();
         //State = er.Message.ToString();
         StatBar.Text = er.Message.ToString();
     }
 }
コード例 #6
0
        // job steady - yellow kontrol
        public bool lambaJobIlgiliIsikSteadyYakSariReworkKontrol(ushort DeviceID, ushort jobStateReworkAnimationID, ushort jobStateReworkColorID, ModbusIpMaster master)
        {
            bool sonuc = false;

            try
            {
                ushort[] value = new ushort[4];
                value[0] = DeviceID; //device ID
                value[1] = 0;        //okuma
                value[2] = 8701;     //
                value[3] = 3;        // adet

                master.WriteMultipleRegisters(1, 699, value);

                ushort[] value2 = new ushort[3];
                value2 = master.ReadHoldingRegisters(1, 713, 3);

                if (value2[0] == 1 && value2[1] == jobStateReworkAnimationID && value2[2] == jobStateReworkColorID)
                {
                    sonuc = true;
                }
                else
                {
                    sonuc = false;
                }
            }
            catch
            {
            }

            return(sonuc);
        }
コード例 #7
0
        public MainPage()
        {
            this.InitializeComponent();

            for (int login = 0; login < MaxLogin; login++) //login logic, if login does not succeed the first time, it will try to reconnect 3 times.
            {
                try
                {
                    Connect();
                }
                catch (Exception)
                {
                    throw;
                }
            }


            for (int cycles = 0; cycles < MaxCycles; cycles++) //logic for capturing and sending data to cloud service
            {
                UInt16[] modbusint = master.ReadHoldingRegisters(1, 1);

                SqlConnection sqlconn = new SqlConnection("Server = tcp:modbusserver.database.windows.net,1433; Initial Catalog = ModbusDB; Persist Security Info = False; User ID = myadmin; Password =(YourPasswordHere); MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 30;");
                sqlconn.Open();                                                                      //opents the sql connection
                string query = "INSERT INTO SensorData (ApplicationType, PressureData, logtimeapp)"; //specifies the query sent to the database, what columns to target
                query += " VALUES (@ApplicationType, @PressureData, @logtimeapp)";
                SqlCommand cmd = new SqlCommand(query, sqlconn);
                cmd.Parameters.AddWithValue("@logtimeapp", DateTime.Now);
                cmd.Parameters.AddWithValue("@PressureData", Convert.ToInt32(modbusint[0]));
                cmd.Parameters.AddWithValue("@ApplicationType", "RaspberryPi_UWP");

                cmd.ExecuteNonQuery();
                sqlconn.Close();
                System.Threading.Thread.Sleep(PollingCycle);
            }
        }
コード例 #8
0
        /*
         * Reads Holding Register values based on the address received from the 'textReadModbusAddress' and
         * the count of the holding registers to be read from 'txtReadModbusCount'.
         * */
        private void btnReadRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Taking ip from the text box and connects to port 502 of the slave.
                using (TcpClient client = new TcpClient(txtIPAddress.Text, 502))
                {
                    // Clearing register values to be read
                    txtReadRegisterValue.Text = "";

                    // Establishing a connection between the master and slave.
                    ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                    // Assign Modbus-StartAddress and number of registers to be read
                    ushort StartAddress  = Convert.ToUInt16(textReadModbusAddress.Text);
                    ushort RegisterCount = Convert.ToUInt16(txtReadModbusCount.Text);

                    // read input register values
                    ushort[] values = master.ReadHoldingRegisters(StartAddress, RegisterCount);

                    //Write the register value/s in the textbox.
                    foreach (ushort us in values)
                    {
                        txtReadRegisterValue.Text += us.ToString() + "; ";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #9
0
        /// <summary>
        ///     Simple Modbus TCP master read inputs example.
        /// </summary>
        public static void ModbusTcpMasterReadInputs()
        {
            using (TcpClient client = new TcpClient("127.0.0.1", 502))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                // read five input values
                ushort startAddress = 0;
                ushort numInputs    = 10;

                var    mc     = master.ReadHoldingRegisters(startAddress, numInputs);
                bool[] inputs = master.ReadInputs(startAddress, numInputs);
                //master.ReadHoldingRegisters

                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Input {(startAddress + i)}={(inputs[i] ? 1 : 0)}");
                }
            }

            // output:
            // Input 100=0
            // Input 101=0
            // Input 102=0
            // Input 103=0
            // Input 104=0
        }
コード例 #10
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 = 3204;//100;
                ushort numInputs    = 5;
                // bool[] inputs = master.ReadInputs(startAddress, numInputs);
                ushort[] PO = master.ReadHoldingRegisters(startAddress, numInputs);

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

            // output:
            // Input 100=0
            // Input 101=0
            // Input 102=0
            // Input 103=0
            // Input 104=0
        }
コード例 #11
0
        /// <summary>
        /// Simple Modbus TCP master read holding registers
        /// Modbus协议函数功能3,读取保持寄存器(16位)
        /// startAddress:起始偏移量(从0开始计数)
        /// numInputs:读取的寄存器个数
        /// holdregs:存放结果用的数组
        /// 读回结果以UINT16为单位存放在数组里(以电表的16位寄存器为单位存放)
        /// </summary>
        public void ReadHoldingRegisters(ushort startAddress, ushort numInputs, ushort[] holdregs)
        {
            ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

            // read read holding registers读保持寄存器(Fun3)
            holdregs = master.ReadHoldingRegisters(startAddress, numInputs);
        }
コード例 #12
0
ファイル: TaskForm.cs プロジェクト: ChengHeAGV/Dbus_Client
        /// <summary>
        /// 同步Modbus设备数据
        /// </summary>
        private void SyncModbus()
        {
            while (true)
            {
                Thread.Sleep(TaskData.Parameter.SyncModbusTime);
                try
                {
                    //读取Modbus寄存器
                    TaskData.Modbus = modbusMaster.ReadHoldingRegisters(0, (ushort)TaskData.Modbus.Length);

                    //Random rd = new Random();
                    //ushort[] write = new ushort[10];
                    //for (int i = 0; i < 10; i++)
                    //{
                    //    write[i] = (ushort)rd.Next(1, 1000);
                    //}
                    //modbusMaster.WriteMultipleRegisters(0, write);
                    //ushort[] read = new ushort[10];
                    //// read = master.ReadWriteMultipleRegisters(0, 10, 0, write);

                    //read = modbusMaster.ReadHoldingRegisters(10, 10);
                    //UdpSever.Shell.WriteNotice("debug", "{0},{1}", read[0], read[1]);
                }
                catch (Exception ex)
                {
                    UdpSever.Shell.WriteError("debug", ex.ToString());
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// 读取03 Holding Regyster (4x) AO的值
        /// </summary>
        /// <param name="address">IP</param>
        /// <param name="port">端口号</param>
        /// <param name="SlaveID">从站地址 (8位)</param>
        /// <param name="startAddress">起始地址 (16位)</param>
        /// <param name="numInputs">读取数量 (16位)</param>
        /// <returns>List</returns>
        public static List <int> HoldingRegister(ushort startAddress, ushort numInputs, byte SlaveID = 1)
        {
            List <int> HoldingList = new List <int>();

            Client.SendTimeout = 1;
            ModbusIpMaster master = ModbusIpMaster.CreateIp(Client);

            try
            {
                ushort[] inputs = master.ReadHoldingRegisters(SlaveID, startAddress, numInputs);
                for (int i = 0; i < numInputs; i++)
                {
                    // 将读取出的数据存储到List中
                    HoldingList.Add(inputs[i]);
                }
                return(HoldingList);
            }
            catch (Exception)
            {
                Client.Close();
                return(new List <int>()
                {
                    -99
                });
            }
        }
コード例 #14
0
 private static void ReadAnalog()
 {
     Console.Clear();
     Console.WriteLine("Retrieving Values, Please Wait");
     if (CheckConnection(IpAddress, 100))
     {
         ushort[] regData;
         using (TcpClient client = new TcpClient(IpAddress, 502)) {
             ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
             regData = master.ReadHoldingRegisters(0, 16);
             client.Close();
         }
         Console.WriteLine();
         Console.WriteLine("Analog Values");
         for (int i = 0; i < regData.Length; i++)
         {
             double x = regData[i];
             x = (x / 1000);
             double y       = SlopeValues2[i] * x + OffsetValues2[i];
             double current = (RValues2[i] != 0) ? (y / RValues2[i]) * 1000 : 0.00;
             Console.WriteLine(" A{0}: Voltage: {1} Current: {2}", i, Math.Round(y, 3), Math.Round(current, 3));
             //Console.WriteLine(" A{0}: Voltage: {1}", i,Math.Round(x,3));
         }
         Console.WriteLine();
         Console.WriteLine("Press any key to continue");
         Console.ReadKey();
     }
     else
     {
         Console.WriteLine("Connection Failed");
     }
 }
コード例 #15
0
        private ushort[] ModbusRead()
        {
            Error(false);
            try
            {
                startAddress = ushort.Parse(textBox_startAddress.Text);
                numInputs    = ushort.Parse(textBox_numInputs.Text);
                slaveID      = byte.Parse(textBox_SlaveID.Text);
                ushort[] datas = new ushort[numInputs];


                switch (comboBox_FunCode.SelectedIndex)
                {
                case 0:
                    bool[] coils = master.ReadCoils(slaveID, startAddress, numInputs);
                    for (int i = 0; i < numInputs; i++)
                    {
                        datas[i] = (ushort)(coils[i] ? 1 : 0);
                    }

                    break;

                case 1:

                    bool[] inputs = master.ReadInputs(slaveID, startAddress, numInputs);
                    for (int i = 0; i < numInputs; i++)
                    {
                        datas[i] = (ushort)(inputs[i] ? 1 : 0);
                    }
                    break;

                case 2:
                    ushort[] holdingRegisters = master.ReadHoldingRegisters(slaveID, startAddress, numInputs);
                    datas = holdingRegisters;
                    break;

                case 3:
                    ushort[] inputRegisters = master.ReadInputRegisters(slaveID, startAddress, numInputs);
                    datas = inputRegisters;
                    break;

                default:
                    MessageBox.Show("功能码错误");
                    datas = null;
                    break;
                }
                txt_show.AppendText("\r\nModbusRead Success");
                return(datas);
            }
            catch (Exception eee)
            {
                Error(true, eee);
                return(null);
            }
        }
コード例 #16
0
        private void RefreshValues()
        {
            lock (_locker)
            {
                {
                    if (ConnectionState == ConnectionStates.Online)
                    {
                        if (_master.Transport != null)
                        {
                            bool[] readCoils = _master.ReadCoils(1, 0, 50);

                            AutoManual       = readCoils[16];
                            RoterMoveing     = readCoils[17];
                            RoteryPosMoveing = readCoils[18];
                            ShorterMoveing   = readCoils[19];

                            ShorterGripperState  = readCoils[12];
                            ShorterCylinderState = readCoils[13];
                            MainGripperState     = readCoils[14];


                            AligmentCheck      = readCoils[27];
                            CrackCheck         = readCoils[28];
                            DustCheck          = readCoils[29];
                            TestResultState    = readCoils[30];
                            VisiontestComplete = readCoils[31];



                            ushort[] readHoldingRegister = _master.ReadHoldingRegisters(1, 0, 50);

                            InletPumpSpeed  = Convert.ToInt32(readHoldingRegister[40]);
                            OutletPumpSpeed = Convert.ToInt32(readHoldingRegister[41]);

                            ReadRoterJogSpeed = Convert.ToInt32(readHoldingRegister[1]);
                            ReadRoterPosSpeed = Convert.ToInt32(readHoldingRegister[2]);
                            ReadRoterCmdPos   = Convert.ToInt32(readHoldingRegister[3]);

                            ReadRoteryPosJogSpeed = Convert.ToInt32(readHoldingRegister[7]);
                            ReadRoteryPosPosSpeed = Convert.ToInt32(readHoldingRegister[6]);
                            ReadRoteryPosCmdPos   = Convert.ToInt32(readHoldingRegister[5]);

                            ReadShorterJogSpeed = Convert.ToInt32(readHoldingRegister[12]);
                            ReadShorterPosSpeed = Convert.ToInt32(readHoldingRegister[13]);
                            ReadShorterCmdPos   = Convert.ToInt32(readHoldingRegister[14]);

                            ProductselectedCount = Convert.ToInt32(readHoldingRegister[28]);
                            TotalPartCount       = Convert.ToInt32(readHoldingRegister[29]);
                            GoodPartCount        = Convert.ToInt32(readHoldingRegister[30]);
                            NotGoodPartCount     = Convert.ToInt32(readHoldingRegister[31]);
                        }
                    }
                }
            }
        }
コード例 #17
0
ファイル: Main.cs プロジェクト: StepSt/M_L
        private void btnReadRegister_Click(object sender, EventArgs e)
        {
            using (TcpClient client = new TcpClient(txtIPAddress.Text, 502))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                ushort startAddress = Convert.ToUInt16(txtReadModbusAddress.Text);
                ushort numInputs    = Convert.ToUInt16(txtReadModbusCount.Text);
                byte   slaveID      = Convert.ToByte(txtSlaveId.Text);
                try
                {
                    ushort[] inputs = master.ReadHoldingRegisters(slaveID, startAddress, numInputs);
                    try
                    {
                        switch (cbTypes.SelectedIndex)
                        {
                        case 0:
                            foreach (ushort us in inputs)
                            {
                                txtReadRegisterValue.Text = us.ToString();
                            }
                            break;

                        case 1:
                            // Из 2-х прочитанных ushort собираем 1 float
                            txtReadRegisterValue.Text = BitConverter.ToSingle(BitConverter.GetBytes(inputs[0]).Concat(BitConverter.GetBytes(inputs[1])).ToArray(), 0).ToString();
                            _logger.Log(LogLevel.Info, "Прочитал значнеи типа float " + txtReadRegisterValue.Text);
                            break;

                        case 2:
                            // Из 2-х прочитанных ushort собираем 1 float inverse
                            txtReadRegisterValue.Text = BitConverter.ToSingle(BitConverter.GetBytes(inputs[1]).Concat(BitConverter.GetBytes(inputs[0])).ToArray(), 0).ToString();
                            _logger.Log(LogLevel.Info, "Прочитал значнеи типа float inverse " + txtReadRegisterValue.Text);
                            break;

                        default:
                            MessageBox.Show("Выберете тип переменной!");
                            break;
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        MessageBox.Show("Размер не может быть =1");
                    }
                }
                catch (SlaveException ex)
                {
                    txtReadMessege.Text  = Convert.ToString(ex.FunctionCode) + ";";
                    txtReadMessege.Text += Convert.ToString(ex.SlaveExceptionCode) + ";";
                }
            }
        }
コード例 #18
0
        public void ModbusUdpSlave_MultipleMasters()
        {
            Random    randomNumberGenerator = new Random();
            bool      master1Complete       = false;
            bool      master2Complete       = false;
            UdpClient masterClient1         = new UdpClient();

            masterClient1.Connect(ModbusMasterFixture.DefaultModbusIPEndPoint);
            ModbusIpMaster master1 = ModbusIpMaster.CreateIp(masterClient1);

            UdpClient masterClient2 = new UdpClient();

            masterClient2.Connect(ModbusMasterFixture.DefaultModbusIPEndPoint);
            ModbusIpMaster master2 = ModbusIpMaster.CreateIp(masterClient2);

            UdpClient slaveClient = CreateAndStartUdpSlave(ModbusMasterFixture.Port, DataStoreFactory.CreateTestDataStore());

            Thread master1Thread = new Thread(delegate()
            {
                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(randomNumberGenerator.Next(1000));
                    _log.Debug("Read from master 1");
                    Assert.AreEqual(new ushort[] { 2, 3, 4, 5, 6 }, master1.ReadHoldingRegisters(1, 5));
                }
                master1Complete = true;
            });

            Thread master2Thread = new Thread(delegate()
            {
                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(randomNumberGenerator.Next(1000));
                    _log.Debug("Read from master 2");
                    Assert.AreEqual(new ushort[] { 3, 4, 5, 6, 7 }, master2.ReadHoldingRegisters(2, 5));
                }
                master2Complete = true;
            });

            master1Thread.Start();
            master2Thread.Start();

            while (!master1Complete || !master2Complete)
            {
                Thread.Sleep(200);
            }

            slaveClient.Close();
            masterClient1.Close();
            masterClient2.Close();
        }
コード例 #19
0
ファイル: oilmeasure.cs プロジェクト: meiheW/oilMeasure
        public double readvalue()
        {
            //从modusb里度一个数值,具体地址从配置文件中读入

            //The first one is used to read coils, the rest read registers
            //To find out the specific content in ReadMe.txt.
            //bool[] res = master.ReadCoils(oilAddr, 1);
            ushort[] res = master.ReadHoldingRegisters(oilAddr, 1);
            //ushort[] res = master.ReadInputRegisters(oilAddr, 1);
            //bool[] res = master.ReadInputs(oilAddr, 1);

            return((double)res[0]);
            //return 0.0;
        }
コード例 #20
0
        private void ReadValues()
        {
            System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
            myWatch.Start();

            isreading = true;
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.CoilStatuses.Maps != null)
            {
                foreach (var item in myDevice.Collection.CoilStatuses.Maps)
                {
                    bool[] values = master.ReadCoils(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.CoilStatuses.RefreshValues(item, values);
                }
            }
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.InputStatuses.Maps != null)
            {
                foreach (var item in myDevice.Collection.InputStatuses.Maps)
                {
                    bool[] values = master.ReadInputs(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.InputStatuses.RefreshValues(item, values);
                }
            }
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.HoldingRegisters.Maps != null)
            {
                foreach (var item in myDevice.Collection.HoldingRegisters.Maps)
                {
                    ushort[] values = master.ReadHoldingRegisters(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.HoldingRegisters.RefreshValues(item, values);
                }
            }
            if (myDevice != null &&
                myDevice.Collection != null &&
                myDevice.Collection.InputRegisters.Maps != null)
            {
                foreach (var item in myDevice.Collection.InputRegisters.Maps)
                {
                    ushort[] values = master.ReadInputRegisters(myDevice.Id, (ushort)(item.StartAddress - 1), item.Range);
                    myDevice.Collection.InputRegisters.RefreshValues(item, values);
                }
            }
            isreading = false;
            myWatch.Stop();
        }
コード例 #21
0
        //return register values specified by types
        public List <Measurement> getValueOfRegisters(List <Register> registers)
        {
            List <Measurement> measurements = new List <Measurement>();

            try {
                foreach (Register register in registers)
                {
                    if (register.meterModel == this.model)
                    {
                        using (TcpClient client = new TcpClient(this.ip, 502)) {
                            using (ModbusIpMaster master = ModbusIpMaster.CreateIp(client)) {
                                //master.Transport.ReadTimeout = 300;
                                master.Transport.WaitToRetryMilliseconds = 0;
                                master.Transport.Retries = 1;

                                Measurement medicao = new Measurement(register.description, this.id);

                                ushort   startAddress = register.register;
                                ushort[] values       = master.ReadHoldingRegisters(this.address, startAddress, register.numInputs);

                                medicao.value = ModbusUtility.GetSingle(values[1], values[0]);

                                if (this.model.Equals("CCK4100S") && register.description.Equals("V"))
                                {
                                    medicao.value = medicao.value * (88000 / 63.5);
                                }

                                medicao.dateTime = DateTime.Now;
                                measurements.Add(medicao);
                                if (!this.status)
                                {
                                    this.status = true;
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                this.status = false;
                throw new IOException(this.id + " " + this.description + " " + this.model, e);
            } catch (SlaveException e) {
                this.status = false;
                throw new SlaveException(this.id + " " + this.description + " " + this.model, e);
            } catch (SocketException e) { //falha conexão com o IP
                this.status = false;
                throw e;
            }
            return(measurements);
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: koson/ModbusTester-WPF
        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();
                }
            }
        }
コード例 #23
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();
        }
コード例 #24
0
ファイル: ModbusTCP.cs プロジェクト: lulzzz/SmartWorld
        public static ushort[] Read_HoldingRegisters(ushort read_start_addr, ushort num_register)
        {
            num_register    = _numOfHoldingRegister;
            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.ReadHoldingRegisters(read_start_addr, num_register);

            Stop_MBClient();
            Stop_MBServer();
            return(read_result);
        }
コード例 #25
0
ファイル: ModbusMy.cs プロジェクト: alexap87/ModbusAppMKK
        public ushort Run()
        {
            Form1  allarm = new Form1();
            ushort result = 0;

            Timer1 = new System.Timers.Timer(2000);
            Timer1.Start();
            try
            {
                if (NetOk)
                {
                    result = master.ReadHoldingRegisters(60, 1112, 1)[0];
                }
                else
                {
                    dtNow = DateTime.Now;
                    if ((dtNow - dtDisconnect) > TimeSpan.FromSeconds(10))
                    {
                        allarm.Alarm(DateTime.Now.ToString() + ":Start connecting");
                        NetOk = Connect();
                        if (!NetOk)
                        {
                            allarm.Alarm(DateTime.Now.ToString() + ":Connecting fail. Wait for retry");
                            dtDisconnect = DateTime.Now;
                        }
                    }
                    else
                    {
                        allarm.Alarm(DateTime.Now.ToString() + ":Wait for retry connecting");
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Source.Equals("System"))
                {
                    NetOk = false;
                    Console.WriteLine(ex.Message);
                    dtDisconnect = DateTime.Now;
                }
            }

            return(result);
        }
コード例 #26
0
        public ushort[] ReadHoldingRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
        {
            if (!status)
            {
                Connect();
            }

            try
            {
                return(master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints));
            }
            catch (Exception ex)
            {
                status = false;
                AddMessage("Catch exception in function ReadHoldingRegisters(). " + ex.Message,
                           DebugLevel.ExceptionLevel);
                return(null);
            }
        }
コード例 #27
0
        // This method publishes the event (MessageEvent) and read the register, afterwards the message(from the register) will be sent back to WTX120.
        // This method is declared as a virtual method to allow derived class to override the event call.
        //protected virtual void ReadRegisterPublishing(MessageEvent<ushort> e)

        public virtual void ReadRegisterPublishing(DataEvent e) // 25.4 Comment : 'virtual' machte hier probleme beim durchlaufen :o
        {
            // virtual new due to tesing - 3.5.2018
            try
            {
                // Read the data: e.Message's type - ushort[]
                //e.Args = masterParam.ReadHoldingRegisters(this.StartAdress, this.getNumOfPoints);

                e.ushortArgs = _master.ReadHoldingRegisters(StartAdress, NumOfPoints);
                _connected   = true;

                BusActivityDetection?.Invoke(this, new LogEvent("Read successful: Registers have been read"));
            }
            catch (ArgumentException)
            {
                Console.WriteLine("\nNumber of points has to be between 1 and 125.\n");
            }
            catch (InvalidOperationException)
            {
                BusActivityDetection?.Invoke(this, new LogEvent("Read failed : Registers have not been read"));

                _connected = false;

                Connect();
                Thread.Sleep(100);
            }

            _data = e.ushortArgs;

            // copy of the event to avoid that a race condition is prevented, if the former subscriber directly logs off after the last
            // condition( and after if(handler!=null) ) and before the event is triggered.

            //RaiseDataEvent?.Invoke(this, e);

            var handler = RaiseDataEvent;

            //If a subscriber exists:
            if (handler != null)
            {
                handler(this, e);
            }
        }
コード例 #28
0
ファイル: Form1.cs プロジェクト: burakkocyigit/DenemeCSharps
        private void button1_Click(object sender, EventArgs e)
        {
            bool      ok;
            ushort    adrx      = 0;
            ushort    adry      = 1;
            ushort    adrz      = 2;
            ushort    adrh      = 3;
            ushort    adrok     = 0;
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect("192.168.0.1", 502);
            ModbusIpMaster master = ModbusIpMaster.CreateIp(tcpClient);

            ushort x = (ushort)Convert.ToInt32(textBox1.Text);
            ushort y = (ushort)Convert.ToInt32(textBox2.Text);
            ushort z = (ushort)Convert.ToInt32(textBox3.Text);
            ushort h = (ushort)Convert.ToInt32(textBox4.Text);

            if (checkBox1.Checked)
            {
                ok = true;
            }
            else
            {
                ok = false;
            }
            master.WriteSingleRegister(adrx, x);
            master.WriteSingleRegister(adry, y);
            master.WriteSingleRegister(adrz, z);
            master.WriteSingleRegister(adrh, h);
            master.WriteSingleCoil(adrok, ok);

            ushort[] key = new ushort[4];
            key = master.ReadHoldingRegisters(0, 4);
            if (key[3] == 1)
            {
                textBox5.Text = "tamam";
            }
            tcpClient.Close();
            master.Dispose();
        }
コード例 #29
0
        /// <summary>
        /// this returns the orientation relative to position when the MCU configured
        /// </summary>
        /// <returns></returns>
        public Orientation read_Position_offset()
        {
            ushort[] inputs  = MCUModbusMaster.ReadHoldingRegisters(0, 20);
            byte[]   inbytes = new byte[inputs.Length * 2];
            Buffer.BlockCopy(inputs, 0, inbytes, 0, inputs.Length * 2);

            ushort msb, lsvb;

            msb  = inputs[2];
            lsvb = inputs[3];
            int    ofset = lsvb + (msb << 16);
            double azpos = (ofset / (20000 * 500)) * 360;

            msb   = inputs[12];
            lsvb  = inputs[13];
            ofset = lsvb + (msb << 16);
            double elpos = (ofset / (20000 * 50)) * 90;

            return(new Orientation(azpos, elpos));
            //return new Orientation(BitConverter.ToDouble(inbytes, 4), BitConverter.ToDouble(inbytes, 24));
        }
コード例 #30
0
        //return register values specified by types
        public List <Measurement> getValueOfRegisters(List <Register> registers)
        {
            List <Measurement> measurements = new List <Measurement>();

            try {
                using (TcpClient client = new TcpClient(this.ip, 502)) {
                    ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

                    foreach (Register register in registers)
                    {
                        if (register.meterModel == this.model)
                        {
                            Measurement medicao = new Measurement(register.description, this.id);

                            ushort   startAddress = register.register;
                            ushort[] values       = master.ReadHoldingRegisters(this.address, startAddress, register.numInputs);

                            medicao.value = ModbusUtility.GetSingle(values[1], values[0]);

                            if (this.model.Equals("CCK4100S") && register.description.Equals("V"))
                            {
                                medicao.value = medicao.value * (92000 / 66);
                            }

                            medicao.dateTime = DateTime.Now;
                            measurements.Add(medicao);
                            if (!this.status)
                            {
                                this.status = true;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                this.status = false;

                throw new Exception(this.id + " " + this.description + " " + this.model, e);
            }
            return(measurements);
        }