Пример #1
0
        private string GetDataArrayFromRegion(ERegionType eType,
                                              List <List <ushort> > listlistRegion,
                                              ref bool[] regionData)
        {
            List <short[]> listData = new List <short[]>();

            foreach (var listT in listlistRegion)
            {
                for (int j = 0; j < listT.Count; j = j + 5)
                {
                    ushort num;
                    if (((listT.Count - j) * 16) > 80)
                    {
                        num = 80;
                    }
                    else
                    {
                        num = (ushort)((listT.Count - j) * 16);
                    }
                    bool[] bData;
                    try
                    {
                        switch (eType)
                        {
                        case ERegionType.Region_DI:
                        {
                            Thread.Sleep(5);
                            bData = master.ReadInputs(
                                (ushort)(CT2.ECT2Descrites.RegionDI + (listT[j]) * 16),
                                (ushort)num);
                            bData.CopyTo(regionData, listT[j] * 16);
                            break;
                        }

                        case ERegionType.Region_DO:
                        {
                            Thread.Sleep(5);
                            bData = master.ReadCoils(
                                (ushort)(CT2.ECT2Coils.RegionDO + (listT[j]) * 16),
                                (ushort)num);
                            bData.CopyTo(regionData, listT[j] * 16);
                            break;
                        }

                        case ERegionType.Region_AO:
                        case ERegionType.Region_AI:
                        default:
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        return(e.Message);
                        //throw;
                    }
                }
            }
            return("NO_ERR");
        }
Пример #2
0
        public async void sensorOkumaKilitMekanizmasi(string istemciIP, TcpClient client, ModbusIpMaster master)
        {
            //start timer1, timer1.Interval = 1000 ms
            try
            {
                if (NetworkIsOk)
                {
                    #region Master to Slave
                    sensor        = master.ReadInputs(0, 2);
                    lockOnSensor  = sensor[0];
                    lockOffSensor = sensor[1];

                    status         = master.ReadInputs(6, 2);
                    deviceAlarmVar = status[0];
                    motorRun       = status[1];
                    #endregion
                }
                else
                {
                    //retry connecting
                    dtNow = DateTime.Now;
                    if ((dtNow - dtDisconnect) > TimeSpan.FromSeconds(10))
                    {
                        haberlesmeMesaj = (DateTime.Now.ToString() + ":Start connecting");
                        NetworkIsOk     = await ConnectTask(istemciIP, client, master);

                        if (!NetworkIsOk)
                        {
                            haberlesmeMesaj = (DateTime.Now.ToString() + ":Connecting fail. Wait for retry");
                            dtDisconnect    = DateTime.Now;
                        }
                    }
                    else
                    {
                        haberlesmeMesaj = (DateTime.Now.ToString() + ":Wait for retry connecting");
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Source.Equals("System"))
                {
                    //set NetworkIsOk to false and retry connecting
                    NetworkIsOk     = false;
                    haberlesmeMesaj = (ex.Message);
                    dtDisconnect    = DateTime.Now;
                }
            }
        }
Пример #3
0
        /// <summary>
        ///     Simple Modbus TCP master read inputs example.
        /// </summary>
        public async void ModbusTcpMasterReadInputs()
        {
            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);

                // read five input values

                ushort startAddress = ushort.Parse(readRegisterInputBox.Text);

                ushort numInputs = ushort.Parse(readRegisterNumberOfRegistersInputBox.Text);

                bool[] inputs = master.ReadInputs(startAddress, numInputs);

                for (int i = 0; i < numInputs; i++)

                {
                    ResultsTextBox.Text += ($"Input {(startAddress + i)}={(inputs[i] ? 1 : 0)}") + "\r\n";
                }
            }
        }
Пример #4
0
        private void button6_Click(object sender, EventArgs e)
        {
            //connect to modbus...
            TcpClient      tcpClient = ConnectTcpClient();
            ModbusIpMaster master    = ConnectModbusMaster(tcpClient);

            master.Transport.ReadTimeout = Convert.ToInt16(textBox5.Text);

            int    selectedInput = Convert.ToInt16(comboBox3.SelectedIndex.ToString());
            int    startAddress  = 0;
            int    i             = selectedInput + startAddress;
            ushort readAddress   = (ushort)i;

            try
            {
                bool[] inputValue = master.ReadInputs(readAddress, 1);
                textBox2.Text = inputValue[0].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.ToString());
                throw;
            }

            tcpClient.Close();
            master.Dispose();
        }
Пример #5
0
        //*****************************************************************************


        private void readInputs_Click(object sender, EventArgs e)
        {
            //connect to modbus...
            TcpClient      tcpClient = ConnectTcpClient();
            ModbusIpMaster master    = ConnectModbusMaster(tcpClient);

            ushort startAddress = 0;
            ushort numOfPoints  = 16; // 2 x 8 inputs

            master.Transport.ReadTimeout = Convert.ToInt16(textBox5.Text);

            try
            {
                bool[] outputArr = master.ReadInputs(startAddress, numOfPoints);

                listView1.Items.Clear();

                for (int i = 0; i < numOfPoints; i++)
                {
                    int n = i + 1;
                    listView1.Items.Add(comboBox3.Items[i].ToString()).SubItems.Add(outputArr[i].ToString());
                }

                tcpClient.Close();
                master.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.ToString());
                //throw;
            }
        }
Пример #6
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
        }
Пример #7
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);
            }
        }
Пример #8
0
        private static void CommunicationTest()
        {
            TcpClient      client = new TcpClient("127.0.0.1", 502);
            ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

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

            bool[] inputs = master.ReadCoils(startAddress, numInputs);


            // Odczyt cyfrowych
            var digitalInputs = master.ReadInputs(startAddress, 16);

            /// Odczyt analogowych
            var analogInputs = master.ReadInputRegisters(0, 16);

            var numbers = new ushort[] { 55, 66 };

            master.WriteMultipleRegisters(0, numbers);


            // Zapis
            master.WriteSingleCoil(18, true);



            // Zapis do Holding Registers
            master.WriteSingleRegister(1, 254);

            var holding = master.ReadHoldingRegisters(0, 2);

            var digitalInputs2 = master.ReadInputs(startAddress, 16);

            for (int i = 0; i < numInputs; i++)
            {
                Console.WriteLine("Input {0}={1}", startAddress + i, inputs[i] ? 1 : 0);
            }
        }
Пример #9
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();
        }
Пример #10
0
        public static bool[] Read_Inputs(ushort read_start_addr, ushort num_inputs)
        {
            num_inputs      = _numOfInputs;
            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.ReadInputs(read_start_addr, num_inputs);

            Stop_MBClient();
            Stop_MBServer();
            return(read_result);
        }
Пример #11
0
        public bool[] ReadInputs(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
        {
            if (!status)
            {
                Connect();
            }

            try
            {
                return(master.ReadInputs(slaveAddress, startAddress, numberOfPoints));
            }
            catch (Exception ex)
            {
                status = false;
                AddMessage("Catch exception in function ReadInputs(). " + ex.Message, DebugLevel.ExceptionLevel);
                return(null);
            }
        }
Пример #12
0
        public Dictionary <string, object> ReadAll()
        {
            if (MyModFieldStore == null || MyModFieldStore.TheValues.Count == 0)
            {
                return(null);
            }
            var timestamp = DateTimeOffset.Now;
            var dict      = new Dictionary <string, object>();

            dict["Timestamp"] = timestamp;

            // Read configured data items via Modbus
            int tMainOffset   = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "Offset");
            int tSlaveAddress = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "SlaveAddress");
            int tReadWay      = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "ConnectionType");

            foreach (var field in MyModFieldStore.TheValues)
            {
                try
                {
                    int address = field.SourceOffset + tMainOffset;

                    ushort[] data = null;

                    float scale = field.ScaleFactor;
                    if (scale == 0)
                    {
                        scale = 1.0f;
                    }

                    switch (tReadWay)
                    {
                    case 1:
                    {
                        bool[] datab = MyModMaster.ReadCoils((ushort)address, (ushort)field.SourceSize);
                        for (int i = 0; i < field.SourceSize && i < datab.Length; i++)
                        {
                            dict[$"{field.PropertyName}_{i}"] = datab[i];
                        }
                        field.Value = dict[$"{field.PropertyName}_0"];
                    }
                        continue;

                    case 2:
                    {
                        bool[] datab = MyModMaster.ReadInputs((ushort)address, (ushort)field.SourceSize);
                        for (int i = 0; i < field.SourceSize && i < datab.Length; i++)
                        {
                            dict[$"{field.PropertyName}_{i}"] = datab[i];
                        }
                        field.Value = dict[$"{field.PropertyName}_0"];
                    }
                        continue;

                    case 4:
                        data = MyModMaster.ReadInputRegisters((byte)tSlaveAddress, (ushort)address, (ushort)field.SourceSize);
                        break;

                    default:
                        data = MyModMaster.ReadHoldingRegisters((byte)tSlaveAddress, (ushort)address, (ushort)field.SourceSize);
                        break;
                    }
                    if (data == null)
                    {
                        continue;
                    }
                    if (field.SourceType == "float")
                    {
                        var value1 = TypeFloat.Convert(data, TypeFloat.ByteOrder.CDAB);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "float-abcd")
                    {
                        var value1 = TypeFloat.Convert(data, TypeFloat.ByteOrder.ABCD);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "double")
                    {
                        var value1 = TypeDouble.Convert(data, TypeDouble.ByteOrder.ABCD);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "double-cdab")
                    {
                        var value1 = TypeDouble.Convert(data, TypeDouble.ByteOrder.CDAB);
                        dict[field.PropertyName] = value1 / scale;
                    }
                    else if (field.SourceType == "int32")
                    {
                        var value    = TypeInt32.Convert(data);
                        var dblValue = Convert.ToDouble(value);
                        dict[field.PropertyName] = dblValue / scale;
                    }
                    else if (field.SourceType == "int64")
                    {
                        var value    = TypeInt64.Convert(data);
                        var dblValue = Convert.ToDouble(value);
                        dict[field.PropertyName] = dblValue / scale;
                    }
                    else if (field.SourceType == "float32")
                    {
                        var value = TypeFloat.Convert(data, TypeFloat.ByteOrder.SinglePrecIEEE);
                        dict[field.PropertyName] = value / scale;
                    }
                    else if (field.SourceType == "uint16")
                    {
                        var value = TypeUInt16.Convert(data);
                        dict[field.PropertyName] = value / scale;
                    }
                    else if (field.SourceType == "int16")
                    {
                        var value = TheCommonUtils.CInt(data[0]);
                        dict[field.PropertyName] = value / scale;
                    }
                    else if (field.SourceType == "utf8")
                    {
                        var value = TypeUTF8.Convert(data);
                        dict[field.PropertyName] = value;
                    }
                    else if (field.SourceType == "byte")
                    {
                        byte value = (byte)(data[0] & 255);
                        dict[field.PropertyName] = value;
                    }
                    field.Value = dict[field.PropertyName];

                    //dict[$"[{field.PropertyName}].[Status]"] = $"";
                }
                catch (Exception e)
                {
                    try
                    {
                        // Future: convey per-tag status similar to OPC statuscode?
                        //dict[$"[{field.PropertyName}].[Status]"] = $"##cdeError: {e.Message}";
                        TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, $"Error reading property {field.PropertyName}", eMsgLevel.l2_Warning, e.ToString()));
                    }
                    catch { }
                }
            }
            return(dict);
        }
Пример #13
0
 /* 读多个触点(DI) */
 public void ReadInputs(ushort startAddress, ushort numberOfPoints, ref List <bool> list)
 {
     bool[] data;
     data = master.ReadInputs(startAddress, numberOfPoints);
     list = data.ToList();
 }
Пример #14
0
        static void Main(string[] args)
        {
            try{
                /*
                 *  Connecting via TCP
                 */
                TcpClient      client = new TcpClient("192.168.42.114", 502); //IP and port of the TOTUS unit
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                master.Transport.ReadTimeout = 1000;                          //ms


                {
                    // read multiple int16 values
                    string[] totusTemps =
                    {
                        "Thermal/AmbientTemp",
                        "Thermal/AmbientTemp/1hAvg",
                        "Thermal/AmbientHumidity",
                        "Thermal/AmbientHumidity/1hAvg",
                        "Thermal/TopOilTemp",
                        "Thermal/TopOilTemp/1hAvg",
                        "Thermal/BottomOilTemp",
                        "Thermal/BottomOilTemp/1hAvg",
                        "Thermal/TapChangerTemp",
                        "Thermal/TapChangerTemp/1hAvg"
                    };

                    {
                        //read int16 temperatures
                        ushort   numInputs    = 10;
                        byte     slaveID      = 1;
                        ushort   startAddress = 1000;                                                        //select address from Totus Modbus table
                        ushort[] temps        = master.ReadInputRegisters(slaveID, startAddress, numInputs); //*2 because we are reading 2byte unsigned short that needs converted to 4 byte floats

                        for (int i = 0; i < numInputs; i++)
                        {
                            Console.WriteLine("{0} = {1}°C", totusTemps[i], (float)temps[i] / 10); // divide by 10 as specified in Scaling column
                        }
                    }
                }
                {
                    //read alarms
                    byte   slaveID      = 1;
                    ushort numInputs    = 2;
                    ushort startAddress = 100;
                    bool[] alarms       = master.ReadInputs(slaveID, startAddress, numInputs);

                    string[] totusAlarms =
                    {
                        "ALARM/System/HL/State",
                        "ALARM/System/HHLL/State"
                    };
                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("{0} = {1}", totusAlarms[i], alarms[i]);
                    }
                }
                {
                    //read DGA float32 gases
                    string[] totusDGA =
                    {
                        "DGA/SourceA/CH4",
                        "DGA/SourceA/C2H6",
                        "DGA/SourceA/C2H4",
                        "DGA/SourceA/C2H2",
                        "DGA/SourceA/CO",
                        "DGA/SourceA/CO2",
                        "DGA/SourceA/O2",
                        "DGA/SourceA/N2",
                        "DGA/SourceA/H2",
                        "DGA/SourceA/H2O",
                        "DGA/SourceA/TDCG",
                        "DGA/SourceA/THC"
                    };
                    byte     slaveID      = 1;
                    ushort   numInputs    = 12;
                    ushort   startAddress = 2200;                                                                      //select address from Totus Modbus table
                    ushort[] inputsdga    = master.ReadInputRegisters(slaveID, startAddress, (ushort)(numInputs * 2)); //*2 because we are reading 2byte unsigned short that needs converted to 4 byte floats

                    for (int i = 0; i < numInputs; i++)
                    {
                        Console.WriteLine("{0} = {1} ppm", totusDGA[i], Convert2Float(inputsdga[i * 2], inputsdga[i * 2 + 1]));
                    }
                }
                master.Dispose();
            }
            catch (Exception exception)
            {
                //Connection exception
                //No response from server.
                //The server maybe close the connection, or response timeout.
                Console.WriteLine(exception.Message);
            }
            Console.Read();
        }
        private static void ChannelUpdaterThreadProc(object obj)
        {
            try
            {
                ModbusStation self = (ModbusStation)obj;
                for (; ;)
                {
                    try
                    {
                        using (TcpClient client = new TcpClient(self.ipAddress, self.tcpPort))
                        {
                            ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                            for (; ;)
                            {
                                foreach (ModbusBuffer buf in self.buffers)
                                {
                                    ushort startAddress = buf.startAddress;
                                    ushort numInputs    = buf.numInputs;
                                    switch (buf.ModbusDataType)
                                    {
                                    case ModbusDataType.InputRegister:
                                        ushort[] registers = master.ReadInputRegisters(startAddress, numInputs);
                                        DateTime dt        = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                ch.DoUpdate((int)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                ch.DoUpdate((uint)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                ch.DoUpdate((float)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;

                                    case ModbusDataType.Coil:
                                        bool[] inputs = master.ReadCoils(startAddress, numInputs);
                                        dt = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                int val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0);
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                float val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;

                                    case ModbusDataType.Input:
                                        inputs = master.ReadInputs(startAddress, numInputs);
                                        dt     = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                int val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0);
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                float val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0;
                                                ch.DoUpdate(val, dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;

                                    case ModbusDataType.HoldingRegister:
                                        registers = master.ReadHoldingRegisters(startAddress, numInputs);
                                        dt        = DateTime.Now;
                                        foreach (ModbusChannelImp ch in buf.channels)
                                        {
                                            if (ch.Value.GetType() == typeof(int))
                                            {
                                                ch.DoUpdate((int)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(uint))
                                            {
                                                ch.DoUpdate((uint)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                            if (ch.Value.GetType() == typeof(float))
                                            {
                                                ch.DoUpdate((float)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good);
                                            }
                                        }
                                        break;
                                    }
                                }
                                Thread.Sleep(100);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (e is ThreadAbortException)
                        {
                            throw e;
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException)
            {
            }
        }
Пример #16
0
 public bool ReadDiscrete(byte slaveId, ushort address)
 {
     return(master.ReadInputs(slaveId, address, 1)[0]);
 }
Пример #17
0
        override public void Run() // переопределяемая функция запуска програмного потока для обслуживания работающего драйвера ModbusTCPMaster
        {
            do
            {
                // счетчик таймера операций ModbusTCPMaster

                DateTime tm = DateTime.Now;  // переменная хранит начальное время запуска потока
                Util.time = tm;
                if (!device.ready)
                {
                    master.Dispose();
                    tcpClient.Close();
                    device.status = 200;
                    device.ready  = false;
                    break;
                }
                cleanQuery();
                try
                {
                    if (lencoils > 0)
                    {
                        varcoils = master.ReadCoils(0, lencoils);
                    }
                    if (lendi > 0)
                    {
                        vardi = master.ReadInputs(0, lendi);
                    }
                    if (lenir > 0)
                    {
                        ushort stadr = 0;
                        int    len   = lenir;
                        do
                        {
                            ushort lenl = (len > 100) ? (ushort)100 : (ushort)len;
                            ir = master.ReadInputRegisters(stadr, lenl);
                            for (int i = 0; i < lenl; i++)
                            {
                                varir[stadr + i] = ir[i];
                            }
                            stadr += 100;
                            len   -= 100;
                        } while (len > 0);
                    }
                    if (lenhr > 0)
                    {
                        ushort stadr = 0;
                        int    len   = lenhr;
                        do
                        {
                            ushort lenl = (len > 100) ? (ushort)100 : (ushort)len;
                            hr = master.ReadHoldingRegisters(stadr, lenl);
                            //hr = master.ReadHoldingRegisters(stadr, 1000);
                            for (int i = 0; i < lenl; i++)
                            {
                                varhr[stadr + i] = hr[i];
                            }
                            stadr += 100;
                            len   -= 100;
                        } while (len > 0);
                    }
                }
                catch (Exception err)
                {
                    Util.errorTCP();
                    Util.errorMessage(err.Message, description);
                    device.status = err.HResult;
                    master.Dispose();
                    tcpClient.Close();
                    device.status = 200;
                    device.ready  = false;
                    break;
                }
                writeVariable();

                DateTime tmnow = DateTime.Now;                            // переменная хранит время завершения операции в потоке
                int      st    = (int)((tmnow.Ticks - tm.Ticks) / 10000); // если превышено время обхода в 100 миллисекунд генерируется предупреждение с указанием колличества циклов
                                                                          // Util.errorMessage("Время потраченное на операции в ModbusTCPMaster : ", st.ToString());
                                                                          //if (st > device.steptime) { Util.errorMessage("Очень долго...." + st.ToString() + " | step time system=" + device.steptime, "; << ModbusTCPMaster >>"); st = 0; }
                if (st > device.steptime)
                {
                    Util.errorMessage("Время обработки цикла " +
                                      st.ToString() +
                                      " превысило заданный период  " +
                                      device.steptime + "  для устройства ",
                                      description);

                    st = 0;
                }



                else
                {
                    st = device.steptime - st;
                }
                if (st > 0)
                {
                    Thread.Sleep(st);
                }

                //Thread.Sleep(device.steptime);
            } while (true);
        }
Пример #18
0
        //public static void HandleRunningInstance(Process instance)
        //{
        //    // 相同時透過ShowWindowAsync還原,以及SetForegroundWindow將程式至於前景
        //    ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
        //    tcp.F_SetForegroundWindow(instance.MainWindowHandle);
        //}
        long Form1_Load()
        {
            cThirdPartyToolControl tpc = new cThirdPartyToolControl();

            string[] file_name = { "CoilStatus_250_Sync_20160331", "HoldingRegister_250_Sync_20160401", "InputRegister_250_Sync_20160331", "InputStatus_250_Sync_20160401" };

            try
            {
                Process[] processes = Process.GetProcessesByName("ModSim32");
                foreach (Process p in processes)
                {
                    // 關閉目前程序前先等待 1000 毫秒
                    p.WaitForExit(1000);
                    p.CloseMainWindow();
                }
                EventLog.AddLog("Check existed ModSim and Close it");
                System.Threading.Thread.Sleep(1000);

                string str = this.GetType().Assembly.Location;
                str = str.Substring(0, str.LastIndexOf(@"\"));
                string sourceDirName = @"\ModSim";
                string destDirName   = @"c:\ModSim";
                bool   copySubDirs   = true;
                DirectoryCopy(str + sourceDirName, destDirName, copySubDirs);

                string sExePath = Directory.GetCurrentDirectory();  // 如果是用iATester執行初始exe 也是指到iATester執行檔位置
                                                                    // 如果是用初始exe檔直接執行 則是指到初始exe檔執行位置
                string sCurrentFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location);
                //sCurrentFilePath無論用什麼執行 就是指到初始exe檔執行位置
                for (int i = 0; i < file_name.Length; i++)
                {
                    string sourceFile = sCurrentFilePath + "\\ModSim\\" + file_name[i];
                    string destFile   = sExePath + "\\" + file_name[i];
                    EventLog.AddLog("copy " + sourceFile + " to " + destFile);
                    System.IO.File.Copy(sourceFile, destFile, true);
                }
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred Delete ModSim and Move it to C:\ : " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                Process ModSim = new Process();
                // FileName 是要執行的檔案
                ModSim.StartInfo.FileName = @"C:\ModSim\ModSim32.exe";
                ModSim.Start();

                EventLog.AddLog("Excute ModSim");
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred Excute ModSim: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                System.Threading.Thread.Sleep(3000);
                //EventLog.AddLog("enter");
                tpc.F_KeybdEvent(tpc.V_VK_ESCAPE, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                //EventLog.AddLog("wait 1 sec");
                System.Threading.Thread.Sleep(1000);

                foreach (Process pTarget in Process.GetProcesses())
                {
                    if (pTarget.ProcessName == "ModSim32")  // 取得處理序名稱並與指定程序名稱比較
                    {
                        //HandleRunningInstance(pTarget);
                        ShowWindowAsync(pTarget.MainWindowHandle, WS_SHOWNORMAL);
                        tpc.F_SetForegroundWindow((int)pTarget.MainWindowHandle);
                    }
                }

                EventLog.AddLog("Load script");

                //string[] file_name = { "CoilStatus_250_Sync_20160331" };

                for (int i = 0; i < file_name.Length; i++)
                {
                    System.Threading.Thread.Sleep(2000);
                    SendKeys.SendWait("^o");
                    System.Threading.Thread.Sleep(1000);

                    int           iRecipeList_Handle = tpc.F_FindWindow("#32770", "Open");
                    StringBuilder lpString           = new StringBuilder(10);
                    int           bb          = tpc.F_GetWindowText(iRecipeList_Handle, lpString, 100);
                    int           iEnterText2 = tpc.F_FindWindowEx(iRecipeList_Handle, 0, "Edit", "");
                    if (iEnterText2 > 0)
                    {
                        byte[] ch = (ASCIIEncoding.ASCII.GetBytes(file_name[i]));
                        for (int j = 0; j < ch.Length; j++)
                        {
                            //SendMessage(PW, WM_CHAR, ch, 0);
                            tpc.F_PostMessage(iEnterText2, tpc.V_WM_CHAR, ch[j], 0);
                            //System.Threading.Thread.Sleep(100);
                        }
                        tpc.F_PostMessage(iEnterText2, tpc.V_WM_KEYDOWN, tpc.V_VK_RETURN, 0);

                        //tpc.F_PostMessage(iEnterText2, tpc.V_WM_CHAR, 'a', 0);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred Load file: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                EventLog.AddLog("connect to TCP");

                System.Threading.Thread.Sleep(2000);
                SendKeys.SendWait("%c");
                System.Threading.Thread.Sleep(1000);
                SendKeys.SendWait("%c");
                System.Threading.Thread.Sleep(1000);
                tpc.F_KeybdEvent(tpc.V_VK_RETURN, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                System.Threading.Thread.Sleep(1000);
                tpc.F_KeybdEvent(tpc.V_VK_UP, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                System.Threading.Thread.Sleep(1000);
                tpc.F_KeybdEvent(tpc.V_VK_RETURN, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
                System.Threading.Thread.Sleep(2000);
                tpc.F_KeybdEvent(tpc.V_VK_RETURN, 0, tpc.V_KEYEVENTF_EXTENDEDKEY, 0);
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred connect to TCP: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            try
            {
                if (master != null)
                {
                    master.Dispose();
                }
                if (tcpClient != null)
                {
                    tcpClient.Close();
                }
                tcpClient = new TcpClient();
                IAsyncResult asyncResult = tcpClient.BeginConnect(ipAddress, tcpPort, null, null);
                asyncResult.AsyncWaitHandle.WaitOne(3000, true); //wait for 3 sec
                if (!asyncResult.IsCompleted)
                {
                    tcpClient.Close();
                    EventLog.AddLog("Cannot connect to ModSim.");
                    return(-1);
                }
                //tcpClient = new TcpClient(ipAddress, tcpPort);

                // create Modbus TCP Master by the tcp client
                //document->Modbus.Device.Namespace->ModbusIpMaster Class->Create Method
                master = ModbusIpMaster.CreateIp(tcpClient);
                master.Transport.Retries     = 0; //don't have to do retries
                master.Transport.ReadTimeout = 1500;
                //this.Text = "On line " + DateTime.Now.ToString();
                EventLog.AddLog("Connect to ModSim.");

                //read DI(1xxxx), start address=0, points=4
                byte   slaveID = 1;
                bool[] status  = master.ReadInputs(slaveID, 0, 1);
                if ((status[0] == true) || (status[0] == false))
                {
                }
                else
                {
                    EventLog.AddLog("read DI(10001) fail");
                    return(-1);
                }
                //read DO(00001), start address=0, points=1
                bool[] coils = master.ReadCoils(slaveID, 0, 1);
                if ((coils[0] == true) || (coils[0] == false))
                {
                }
                else
                {
                    EventLog.AddLog("read DO(00001) fail");
                    return(-1);
                }
                //read AI(30001), start address=0, points=1
                ushort[] register = master.ReadInputRegisters(1, 0, 1);
                if (register[0] > 0)
                {
                }
                else
                {
                    EventLog.AddLog("read AI(30001) fail");
                    return(-1);
                }
                //read AO(40001), start address=0, points=1
                ushort[] holding_register = master.ReadHoldingRegisters(1, 0, 1);
                if (holding_register[0] > 0)
                {
                }
                else
                {
                    EventLog.AddLog("read AO(40001) fail");
                    return(-1);
                }
            }
            catch (Exception ex)
            {
                EventLog.AddLog(@"Error occurred verification: " + ex.ToString());
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }

            #region Result judgement
            int iTotalSeleniumAction = dataGridView1.Rows.Count;
            for (int i = 0; i < iTotalSeleniumAction - 1; i++)
            {
                DataGridViewRow row             = dataGridView1.Rows[i];
                string          sSeleniumResult = row.Cells[2].Value.ToString();
                if (sSeleniumResult != "PASS")
                {
                    bFinalResult = false;
                    EventLog.AddLog("Test Fail !!");
                    EventLog.AddLog("Fail TestItem = " + row.Cells[0].Value.ToString());
                    EventLog.AddLog("BrowserAction = " + row.Cells[1].Value.ToString());
                    EventLog.AddLog("Result = " + row.Cells[2].Value.ToString());
                    EventLog.AddLog("ErrorCode = " + row.Cells[3].Value.ToString());
                    EventLog.AddLog("ExeTime(ms) = " + row.Cells[4].Value.ToString());
                    break;
                }
            }

            if (bFinalResult)
            {
                Result.Text      = "PASS!!";
                Result.ForeColor = Color.Green;
                EventLog.AddLog("Test Result: PASS!!");
                return(0);
            }
            else
            {
                Result.Text      = "FAIL!!";
                Result.ForeColor = Color.Red;
                EventLog.AddLog("Test Result: FAIL!!");
                return(-1);
            }
            #endregion
        }
Пример #19
0
        private void DataRetrievingThread()
        {
#if DEMO
            Random rnd = new Random();
#endif
            while (true)
            {
                // Get time
                DateTime now = DateTime.Now;
                // Read
                lock (DataContainer.Data.DataQueue)
                {
                    // Register
                    for (int i = 0; i < N3PR.REG_ADDRESS.Count; i++)
                    {
                        try
                        {
                            ushort[] regs = new ushort[2];
#if !DEMO
                            if (N3PR.REG_FUNCTION_CODES[i] == "0x04")
                            {
                                regs = _master.ReadInputRegisters(N3PR.REG_ADDRESS[i], 1);
                            }
                            else if (N3PR.REG_FUNCTION_CODES[i] == "0x02")
                            {
                                bool[] _hh = _master.ReadInputs(N3PR.REG_ADDRESS[i], 1);
                                for (int j = 0; j < _hh.Count(); j++)
                                {
                                    regs[j] = Convert.ToUInt16(_hh[j]);
                                }
                            }
#endif
                            if (regs != null && regs.Count() > 0)
                            {
#if DEMO
                                var mp = new MeasurePoint
                                {
                                    Date     = now,
                                    Reg_Name = N3PR.REG_NAMES[i],
                                    b_val    = Convert.ToBoolean(rnd.Next(0, 2)),
                                    i_val    = Convert.ToInt32((uint)rnd.Next(0, 32766)),
                                    ui_val   = (uint)rnd.Next(0, 65535)
                                };
                                DataContainer.Data.DataQueue.Add(mp);
#else
                                if (regs[0] < 32766)
                                {
                                    var mp = new MeasurePoint
                                    {
                                        Date     = now,
                                        Reg_Name = N3PR.REG_NAMES[i],
                                        b_val    = Convert.ToBoolean(regs[0]),
                                        i_val    = Convert.ToInt32(regs[0]),
                                        ui_val   = (uint)regs[0]
                                    };
                                    DataContainer.Data.DataQueue.Add(mp);
                                }
                                else
                                {
                                    var mp = new MeasurePoint
                                    {
                                        Date     = now,
                                        Reg_Name = N3PR.REG_NAMES[i],
                                        b_val    = Convert.ToBoolean(regs[0]),
                                        i_val    = Convert.ToInt32(regs[0] - 65532),
                                        ui_val   = (uint)regs[0]
                                    };
                                    DataContainer.Data.DataQueue.Add(mp);
                                }
#endif
                                OnDataReceivedEvent?.Invoke(this, null);
                            }
                        }
                        catch
                        {
                            Status = "Error reading Data ModBus register.\n";
                            return;
                        }
                    }
                }
                Thread.Sleep(1000 * FreqReadSec);
            }
        }