Ejemplo n.º 1
0
        public void Multivars()
        {
            var bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            var index = 30;

            Server.RegisterArea(S7Server.SrvAreaDB, index, ref bytes, bytes.Length);

            var buffer   = new byte[bytes.Length];
            var multivar = new S7MultiVar(Client);

            multivar.ShouldNotBeNull();

            multivar.Add(new Sharp7.S7Consts.S7Tag()
            {
                Area = (int)S7Area.DB, DBNumber = index, Elements = 2, Start = 0, WordLen = 2
            }, ref buffer).ShouldBe(true);

            multivar.Read().ShouldBe(0);
            multivar.Add(new Sharp7.S7Consts.S7Tag()
            {
                Area = (int)S7Area.DB, DBNumber = index, Elements = 2, Start = 0, WordLen = 2
            }, ref buffer).ShouldBe(true);

            multivar.Write().ShouldBe(0);
        }
Ejemplo n.º 2
0
        public List <int> ReadQuantityMQCProduced()
        {
            List <int> listQuantity = new List <int>();

            try
            {
                S7MultiVar Reader = new S7MultiVar(Client);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.DInt, 6, 4, 2, ref DB_A);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.DInt, 6, 6, 2, ref DB_B);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.DInt, 6, 8, 2, ref DB_C);
                var Result = Reader.Read();
                var intOK  = Sharp7.S7.GetDIntAt(DB_A, 2);
                var intNG  = Sharp7.S7.GetDIntAt(DB_B, 0);
                var intRW  = Sharp7.S7.GetDIntAt(DB_C, 0);
                listQuantity.Add(intOK);
                listQuantity.Add(intNG);
                listQuantity.Add(intRW);
                return(listQuantity);
            }
            catch (Exception ex)
            {
                SystemLog.Output(SystemLog.MSG_TYPE.Err, "Read Quantity fail", ex.Message);
            }
            return(listQuantity);
        }
Ejemplo n.º 3
0
        public Dictionary <string, bool> ReadStatusPLCMQC()
        {
            Dictionary <string, bool> keyValuePairs = new Dictionary <string, bool>();

            keyValuePairs.Add(PLC2.VariablePLC.FlagKT, false);
            keyValuePairs.Add(PLC2.VariablePLC.IsReset, false);
            keyValuePairs.Add(PLC2.VariablePLC.OnOFF, false);
            keyValuePairs.Add(PLC2.VariablePLC.WriteReadyStart, false);
            try
            {
                S7MultiVar Reader = new S7MultiVar(Client);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.Byte, 7, 2048, 1, ref DB_A);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.Byte, 181, 208, 1, ref DB_B);
                //Client.ReadArea(S7Area.DB, 181, 204, 1, S7WordLength.Byte, Buffer);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.Byte, 9, 0, 1, ref DB_C);
                Reader.Add((int)S7Area.DB, (int)S7WordLength.Byte, 181, 204, 1, ref DB_D);
                var Result = Reader.Read();
                keyValuePairs[PLC2.VariablePLC.FlagKT]          = Sharp7.S7.GetBitAt(DB_A, 0, 0);
                keyValuePairs[PLC2.VariablePLC.IsReset]         = Sharp7.S7.GetBitAt(DB_B, 0, 0);
                keyValuePairs[PLC2.VariablePLC.OnOFF]           = Sharp7.S7.GetBitAt(DB_C, 0, 2);
                keyValuePairs[PLC2.VariablePLC.WriteReadyStart] = Sharp7.S7.GetBitAt(DB_D, 0, 0);


                return(keyValuePairs);
            }
            catch (Exception ex)
            {
                SystemLog.Output(SystemLog.MSG_TYPE.Err, "Read Quantity fail", ex.Message);
            }
            return(keyValuePairs);
        }
Ejemplo n.º 4
0
        public async Task <Dictionary <string, byte[]> > ExecuteMultiVarRequest(IEnumerable <string> variableNames)
        {
            var enumerable = variableNames as string[] ?? variableNames.ToArray();

            if (enumerable.IsEmpty())
            {
                return(new Dictionary <string, byte[]>());
            }

            var s7MultiVar = new S7MultiVar(sharp7);

            var buffers = enumerable.Select(key => new { VariableName = key, Address = s7VariableAddresses.GetOrAdd(key, s => variableNameParser.Parse(s)) })
                          .Select(x =>
            {
                var buffer = new byte[x.Address.Length];
                s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, x.Address.DbNr, x.Address.Start, x.Address.Length, ref buffer);
                return(new { x.VariableName, Buffer = buffer });
            })
                          .ToArray();

            var result = await Task.Factory.StartNew(() => s7MultiVar.Read(), CancellationToken.None, TaskCreationOptions.None, scheduler);

            if (result != 0)
            {
                await EvaluateErrorCode(result);

                throw new InvalidOperationException($"Error in MultiVar request for variables: {string.Join(",", enumerable)}");
            }

            return(buffers.ToDictionary(arg => arg.VariableName, arg => arg.Buffer));
        }
        public Task SetInf(int add)
        {
            return(Task.Run(() =>
            {
                {
                    var s7multivar3 = new S7MultiVar(_client);
                    byte[] buffer189 = new byte[20];
                    string INFSTSPVL = INFSETPOINTVL;
                    string IQFSTSPVL = IQFSETPOINTVL;
                    string GLZSTSPVL = GLZSETPOINTVL;
                    string HDSTSPVL = HDSETPOINTVL;
                    string RFSTSPVL = RFSETPOINTVL;
                    float INF_ST_SP2;

                    if (add == 0)
                    {
                        INF_ST_SP2 = float.Parse(INFSTSPVL);
                        INF_ST_SP2 = Convert.ToSingle(INFSTSPVL);
                        tam1 = INF_ST_SP2;
                    }

                    if (add == 1)
                    {
                        INF_ST_SP2 = float.Parse(IQFSTSPVL);
                        INF_ST_SP2 = Convert.ToSingle(IQFSTSPVL);
                        tam2 = INF_ST_SP2;
                    }

                    if (add == 2)
                    {
                        INF_ST_SP2 = float.Parse(GLZSTSPVL);
                        INF_ST_SP2 = Convert.ToSingle(GLZSTSPVL);
                        tam3 = INF_ST_SP2;
                    }

                    if (add == 3)
                    {
                        INF_ST_SP2 = float.Parse(HDSTSPVL);
                        INF_ST_SP2 = Convert.ToSingle(HDSTSPVL);
                        tam4 = INF_ST_SP2;
                    }

                    if (add == 4)
                    {
                        INF_ST_SP2 = float.Parse(RFSTSPVL);
                        INF_ST_SP2 = Convert.ToSingle(RFSTSPVL);
                        tam5 = INF_ST_SP2;
                    }

                    s7multivar3.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 189, 0, buffer189.Length, ref buffer189);
                    S7.SetRealAt(buffer189, 0, (float)tam1);
                    S7.SetRealAt(buffer189, 4, (float)tam2);
                    S7.SetRealAt(buffer189, 8, (float)tam3);
                    S7.SetRealAt(buffer189, 12, (float)tam4);
                    S7.SetRealAt(buffer189, 16, (float)tam5);
                    int result89 = s7multivar3.Write();
                }
            }));
        }
Ejemplo n.º 6
0
        public void DBMultiRead()
        {
            // Multi Reader Instance
            S7MultiVar Reader = new S7MultiVar(Client);

            TxtRes_A.Text = "";
            TxtRes_B.Text = "";
            TxtRes_C.Text = "";

            int DBNumber_A = System.Convert.ToInt32(TxtDB_A.Text);
            int DBNumber_B = System.Convert.ToInt32(TxtDB_B.Text);
            int DBNumber_C = System.Convert.ToInt32(TxtDB_C.Text);

            // Add Items def.
            Reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_A, 0, 16, ref DB_A);
            Reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_B, 0, 16, ref DB_B);
            Reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_C, 0, 16, ref DB_C);

            // Performs the Read
            int Result = Reader.Read();

            // Dumps the data and shows the results
            ShowResult(Result);


            TxtRes_A.Text = Client.ErrorText(Reader.Results[0]);
            if (Reader.Results[0] == 0)
            {
                HexDump(TxtDump_A, DB_A, 16);
            }
            else
            {
                TxtDump_A.Text = "< No Data Available >";
            }

            TxtRes_B.Text = Client.ErrorText(Reader.Results[1]);
            if (Reader.Results[1] == 0)
            {
                HexDump(TxtDump_B, DB_B, 16);
            }
            else
            {
                TxtDump_B.Text = "< No Data Available >";
            }

            TxtRes_C.Text = Client.ErrorText(Reader.Results[2]);
            if (Reader.Results[2] == 0)
            {
                HexDump(TxtDump_C, DB_C, 16);
            }
            else
            {
                TxtDump_C.Text = "< No Data Available >";
            }
        }
Ejemplo n.º 7
0
    //-------------------------------------------------------------------------
    // MultiRead
    //-------------------------------------------------------------------------
    static void MultiRead()
    {
        int Size = 16;
        // Multi Reader Instance
        S7MultiVar Reader = new S7MultiVar(Client);

        // Add Items def.
        Reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_A, 0, Size, ref DB_A);
        Reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_B, 0, Size, ref DB_B);
        Reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_C, 0, Size, ref DB_C);
        // Performs the Read
        int res = Reader.Read();

        if (Check(res, "Multi Read in a single telegram"))
        {
            if (Reader.Results[0] == 0)
            {
                Console.WriteLine("Dump : " + Size.ToString() + " bytes from DB " + DBNumber_A.ToString());
                HexDump(DB_A, Size);
            }
            else
            {
                Console.WriteLine("DB " + DBNumber_A.ToString() + " " + Client.ErrorText(Reader.Results[0]));
            }

            if (Reader.Results[1] == 0)
            {
                Console.WriteLine("Dump : " + Size.ToString() + " bytes from DB " + DBNumber_B.ToString());
                HexDump(DB_B, Size);
            }
            else
            {
                Console.WriteLine("DB " + DBNumber_B.ToString() + " " + Client.ErrorText(Reader.Results[0]));
            }

            if (Reader.Results[2] == 0)
            {
                Console.WriteLine("Dump : " + Size.ToString() + " bytes from DB " + DBNumber_C.ToString());
                HexDump(DB_C, Size);
            }
            else
            {
                Console.WriteLine("DB " + DBNumber_C.ToString() + " " + Client.ErrorText(Reader.Results[0]));
            }
        }
    }
Ejemplo n.º 8
0
        /// <summary>
        /// Read all GI from PLC.
        /// </summary>
        /// <param name="component"></param>
        private void Read(SmartComponent component)
        {
            if (client.Connected)
            {
                S7MultiVar reader = new S7MultiVar(client);

                bool          allDI_OK = true;
                int           diCount  = (int)component.Properties["DI_Number"].Value;
                List <byte[]> list     = new List <byte[]>();
                for (int i = 0; i < diCount; ++i)
                {
                    S7Client.S7DataItem item = new S7Client.S7DataItem();
                    allDI_OK &= GetS7DataItem((string)component.Properties["DI_Address_" + i.ToString()].Value, ref item);
                    if (allDI_OK)
                    {
                        byte[] b = new byte[1];
                        list.Add(b);
                        if (!reader.Add(item.Area, item.WordLen, item.DBNumber, item.Start, item.Amount, ref b))
                        {
                            ShowResult(component, 0x00200000);                            // S7Consts.errCliInvalidParams
                        }
                    }
                }

                if (allDI_OK && (diCount > 0))
                {
                    int result = 0x01700000;                    // S7Consts.errCliInvalidBlockType
                    result = reader.Read();
                    ShowResult(component, result);
                    if (result == 0)
                    {
                        for (int i = 0; i < diCount; ++i)
                        {
                            ShowResult(component, reader.Results[i]);
                            string giName = "DI_" + i.ToString();
                            if (component.IOSignals.Contains(giName))
                            {
                                byte[] b = list[i];
                                component.IOSignals[giName].Value = ((int)b[0] != 0 ? 1 : 0);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Read all DI from PLC.
        /// </summary>
        /// <param name="smartComponent"></param>
        private void Read(SmartComponent smartComponent)
        {
            if (client.Connected)
            {
                S7MultiVar reader = new S7MultiVar(client);

                bool          allDO_OK    = true;
                int           doCount     = (int)smartComponent.Properties["DO_Number"].Value;
                List <byte[]> listBuffers = new List <byte[]>();
                for (int i = 0; i < doCount; ++i)
                {
                    S7Client.S7DataItem item = new S7Client.S7DataItem();
                    allDO_OK &= GetS7DataItem((string)smartComponent.Properties["DO_Address_" + i.ToString()].Value, ref item);
                    if (allDO_OK)
                    {
                        byte[] buffer = new byte[1];
                        listBuffers.Add(buffer);
                        if (!reader.Add(item.Area, item.WordLen, item.DBNumber, item.Start, item.Amount, ref buffer))
                        {
                            LogError(smartComponent, S7Consts.errCliInvalidParams);
                        }
                    }
                }

                if (allDO_OK && (doCount > 0))
                {
                    int err = S7Consts.errCliInvalidBlockType;
                    err = reader.Read();
                    LogError(smartComponent, err);
                    if (err == 0)
                    {
                        for (int i = 0; i < doCount; ++i)
                        {
                            LogError(smartComponent, reader.Results[i]);
                            string diName = "DO_" + i.ToString();
                            if (smartComponent.IOSignals.Contains(diName))
                            {
                                byte[] buffer = listBuffers[i];
                                smartComponent.IOSignals[diName].Value = ((int)buffer[0] != 0 ? 1 : 0);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
        private void CreateReader(List <S7AlarmDefinition> partialAlarmsDefinitionsList)
        {
            //create reader
            _reader = new S7MultiVar(PLC);

            //adding tags
            for (int i = 0; i < partialAlarmsDefinitionsList.Count(); i++)
            {
                //alarm tag
                byte[] alarmTag = _obtainedDataAlarm[i];
                _reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, partialAlarmsDefinitionsList[i].AlarmTagDBnumber,
                            partialAlarmsDefinitionsList[i].AlarmTagByteNumber, 1, ref alarmTag);

                //acknowledgement tag
                byte[] ackTag = _obtainedDataAck[i];
                _reader.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, partialAlarmsDefinitionsList[i].AckTagDBnumber,
                            partialAlarmsDefinitionsList[i].AckTagByteNumber, 1, ref ackTag);
            }
        }
Ejemplo n.º 11
0
        public void DBMultiRead()
        {
            // Reader Instance
            S7MultiVar Reader = new S7MultiVar(Client);

            TxtRes_A.Text = "";
            TxtRes_B.Text = "";
            TxtRes_C.Text = "";

            int DBNumber_A = System.Convert.ToInt32(TxtDB_A.Text);
            int DBNumber_B = System.Convert.ToInt32(TxtDB_B.Text);
            int DBNumber_C = System.Convert.ToInt32(TxtDB_C.Text);

            // Add Items def.
            Reader.Add(S7Client.S7AreaDB, S7Client.S7WLByte, DBNumber_A, 0, 16, ref DB_A);
            Reader.Add(S7Client.S7AreaDB, S7Client.S7WLByte, DBNumber_B, 0, 16, ref DB_B);
            Reader.Add(S7Client.S7AreaDB, S7Client.S7WLByte, DBNumber_C, 0, 16, ref DB_C);
            // Performs the Read
            int Result = Reader.Read();

            // Dumps the data and shows the results
            ShowResult(Result);

            
            TxtRes_A.Text = Client.ErrorText(Reader.Results[0]);
            if (Reader.Results[0] == 0)
                Dump(TxtDump_A, DB_A, 16);
            else
                TxtDump_A.Text = "< No Data Available >";

            TxtRes_B.Text = Client.ErrorText(Reader.Results[1]);
            if (Reader.Results[1] == 0)
                Dump(TxtDump_B, DB_B, 16);
            else
                TxtDump_B.Text = "< No Data Available >";

            TxtRes_C.Text = Client.ErrorText(Reader.Results[2]);
            if (Reader.Results[2] == 0)
                Dump(TxtDump_C, DB_C, 16);
            else
                TxtDump_C.Text = "< No Data Available >";
        }
Ejemplo n.º 12
0
        void DBMultiWrite()
        {
            for (int c = 0; c < 16; c++)
            {
                DB_A[c] = 0x01;
            }
            for (int c = 0; c < 16; c++)
            {
                DB_B[c] = 0x02;
            }

            // Multi Writer Instance
            S7MultiVar Writer = new S7MultiVar(Client);

            TxtRes_A.Text  = "";
            TxtRes_B.Text  = "";
            TxtRes_C.Text  = "";
            TxtDump_A.Text = "";
            TxtDump_B.Text = "";
            TxtDump_C.Text = "";

            int DBNumber_A = Convert.ToInt32(TxtDB_A.Text);
            int DBNumber_B = Convert.ToInt32(TxtDB_B.Text);
            int DBNumber_C = Convert.ToInt32(TxtDB_C.Text);

            // Add Items def.

            Writer.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_A, 0, 16, ref DB_A);
            Writer.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_B, 0, 16, ref DB_B);
            Writer.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, DBNumber_C, 0, 16, ref DB_C);


            // Performs the Write
            int Result = Writer.Write();

            // Shows the results
            ShowResult(Result);

            TxtRes_A.Text = Client.ErrorText(Writer.Results[0]);
            TxtRes_B.Text = Client.ErrorText(Writer.Results[1]);
            TxtRes_C.Text = Client.ErrorText(Writer.Results[2]);
        }
Ejemplo n.º 13
0
    //PerformGlobalRead() Allows us to import all the PLC outputs.
    public void PerformGlobalRead(S7Client a_Client)
    {
        S7MultiVar Reader = new S7MultiVar(a_Client);

        //Buffers

        //BoolInputs
        Reader.Add(S7Consts.S7AreaPA,             //Area
                   S7Consts.S7WLByte,
                   0,                             //DB, 0 if it's not a db
                   0,                             //Starting byte
                   20,                            //Length of bytes
                   ref BufferBoolOutputs);        //Where to assign
        Reader.Add(S7Consts.S7AreaPA,             //Area
                   S7Consts.S7WLByte,
                   0,                             //DB, 0 if it's not a db
                   256,                           //Starting byte
                   16,                            //Length of bytes
                   ref BufferWordOutputs);        //Where to assign
        int Result = Reader.Read();
    }
Ejemplo n.º 14
0
    //PerformGlobalWrite() Allows us to write at the PLC all the inputs as if they were real inputs
    public void PerformGlobalWrite(S7Client a_Client)
    {
        S7MultiVar Writer = new S7MultiVar(a_Client);

        //BoolInputs
        Writer.Add(S7Consts.S7AreaPE,             //Area
                   S7Consts.S7WLByte,
                   0,                             //DB, 0 if it's not a db
                   0,                             //Starting byte
                   20,                            //Length of bytes
                   ref BufferBoolInputs);         //Where to assign
        Writer.Add(S7Consts.S7AreaPE,             //Area
                   S7Consts.S7WLByte,
                   0,                             //DB, 0 if it's not a db
                   1000,                          //Starting byte
                   24,                            //Length of bytes
                   ref BufferDecimalInputs);      //Where to assign


        int Result = Writer.Write();
        //Check(a_Client, Result, "Writing Operation");
        //Debug.Log("Writer finished with a value of " + Result);
    }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            //-------------- Create and connect the client
            var client = new S7Client();
            int result = client.ConnectTo("127.0.0.1", 0, 1);

            if (result == 0)
            {
                Console.WriteLine("Connected to 127.0.0.1");
            }
            else
            {
                Console.WriteLine(client.ErrorText(result));
                Console.ReadKey();
                return;
            }

            //-------------- Read db1
            Console.WriteLine("\n---- Read DB 1");

            byte[] db1Buffer = new byte[18];
            result = client.DBRead(1, 0, 18, db1Buffer);
            if (result != 0)
            {
                Console.WriteLine("Error: " + client.ErrorText(result));
            }
            int db1dbw2 = S7.GetIntAt(db1Buffer, 2);

            Console.WriteLine("DB1.DBW2: " + db1dbw2);

            double db1dbd4 = S7.GetRealAt(db1Buffer, 4);

            Console.WriteLine("DB1.DBD4: " + db1dbd4);

            double db1dbd8 = S7.GetDIntAt(db1Buffer, 8);

            Console.WriteLine("DB1.DBD8: " + db1dbd8);

            double db1dbd12 = S7.GetDWordAt(db1Buffer, 12);

            Console.WriteLine("DB1.DBD12: " + db1dbd12);

            double db1dbw16 = S7.GetWordAt(db1Buffer, 16);

            Console.WriteLine("DB1.DBD16: " + db1dbw16);

            //-------------- Read DB3
            Console.WriteLine("\n---- Read DB 3");

            byte[] db3Buffer = new byte[18];
            result = client.DBRead(3, 0, 18, db3Buffer);
            if (result != 0)
            {
                Console.WriteLine("Error: " + client.ErrorText(result));
            }
            int db3dbw2 = S7.GetIntAt(db3Buffer, 2);

            Console.WriteLine("DB3.DBW2: " + db3dbw2);

            double db3dbd4 = S7.GetRealAt(db3Buffer, 4);

            Console.WriteLine("DB3.DBD4: " + db3dbd4);

            double db3dbd8 = S7.GetDIntAt(db3Buffer, 8);

            Console.WriteLine("DB3.DBD8: " + db3dbd8);

            uint db3dbd12 = S7.GetDWordAt(db3Buffer, 12);

            Console.WriteLine("DB3.DBD12: " + db3dbd12);

            ushort db3dbd16 = S7.GetWordAt(db3Buffer, 16);

            Console.WriteLine("DB3.DBD16: " + db3dbd16);

            //-------------- Write Db1
            Console.WriteLine("\n---- Write BD 1");

            db1Buffer = new byte[12];
            const int START_INDEX = 4;

            S7.SetRealAt(db1Buffer, 4 - START_INDEX, (float)54.36);
            S7.SetDIntAt(db1Buffer, 8 - START_INDEX, 555666);
            S7.SetDWordAt(db1Buffer, 12 - START_INDEX, 123456);
            result = client.DBWrite(1, START_INDEX, db1Buffer.Length, db1Buffer);
            if (result != 0)
            {
                Console.WriteLine("Error: " + client.ErrorText(result));
            }

            //-------------- Read multi vars
            var s7MultiVar = new S7MultiVar(client);

            byte[] db1 = new byte[18];
            s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 1, 0, db1.Length, ref db1);
            byte[] db3 = new byte[18];
            s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 3, 0, db3.Length, ref db3);
            result = s7MultiVar.Read();
            if (result != 0)
            {
                Console.WriteLine("Error on s7MultiVar.Read()");
            }

            db1dbw2 = S7.GetIntAt(db1, 2);
            Console.WriteLine("DB1.DBW2.0 = {0}", db1dbw2);

            db1dbd4 = S7.GetRealAt(db1, 4);
            Console.WriteLine("DB1.DBW4.0 = {0}", db1dbd4);

            db1dbd8 = S7.GetDIntAt(db1, 8);
            Console.WriteLine("DB1.DBW8.0 = {0}", db1dbd8);

            db3dbw2 = S7.GetIntAt(db3, 2);
            Console.WriteLine("DB3.DBW2.0 = {0}", db3dbw2);

            db3dbd4 = S7.GetRealAt(db3, 4);
            Console.WriteLine("DB3.DBW4.0 = {0}", db3dbd4);

            db3dbd8 = S7.GetDIntAt(db3, 8);
            Console.WriteLine("DB3.DBW8.0 = {0}", db3dbd8);

            //-------------- Write multi vars
            s7MultiVar = new S7MultiVar(client);
            const int DB1_START_INDEX = 2;

            db1 = new byte[10];
            S7.SetIntAt(db1, 2 - DB1_START_INDEX, 50);
            S7.SetRealAt(db1, 4 - DB1_START_INDEX, (float)36.5);
            S7.SetDIntAt(db1, 8 - DB1_START_INDEX, 123456);
            s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 1, DB1_START_INDEX, db1.Length, ref db1);

            const int DB3_START_INDEX = 2;

            db3 = new byte[10];
            S7.SetIntAt(db3, 2 - DB3_START_INDEX, -50);
            S7.SetRealAt(db3, 4 - DB3_START_INDEX, (float)-25.36);
            S7.SetDIntAt(db3, 8 - DB3_START_INDEX, -123456);
            s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 3, DB3_START_INDEX, db3.Length, ref db3);
            result = s7MultiVar.Write();
            if (result != 0)
            {
                Console.WriteLine("Error on s7MultiVar.Read()");
            }

            //-------------- Disconnect the client
            client.Disconnect();
            Console.ReadKey();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Initialize the Driver variables and prepare for connection.</summary>
        public void Initialize()
        {
            bool        retVal = true;
            int         i, j, datSize, SAddress, tAmount;
            DAConfClass thisArea;

            if (!((MasterDriverConf != null) && (Status != null)))
            {
                retVal = false;
                Status.NewStat(StatType.Warning, "Master Objects are Invalid.");
            }

            if (retVal)
            {
                if ((!isInitialized) && (MasterDriverConf.Enable))
                {
                    try
                    {
                        // Client creation
                        Client = new S7Client();

                        //Configure the timeouts
                        //Client.SetParam(S7Consts.p_i32_PingTimeout, ref MasterDriverConf.Timeout);
                        Client.SetParam(S7Consts.p_i32_RecvTimeout, ref MasterDriverConf.Timeout);
                        Client.SetParam(S7Consts.p_i32_SendTimeout, ref MasterDriverConf.Timeout);

                        //Generate the MultiVar Objects
                        Reader = new S7MultiVar(Client);
                        Writer = new S7MultiVar(Client);

                        IntData = new DataExtClass.DataContainer[MasterDriverConf.NDataAreas];

                        j = 0; //Count the enabled Data Areas

                        //Cicle and configure the data areas
                        for (i = 0; i < MasterDriverConf.NDataAreas; i++)
                        {
                            thisArea = MasterDataAreaConf[i];
                            SAddress = int.Parse(thisArea.StartAddress);
                            datSize  = S7Client.S7WLByte; //Always read bytes

                            if (thisArea.Enable)
                            {
                                switch (thisArea.dataType)
                                {
                                case DriverConfig.DatType.Bool:
                                    tAmount          = (int)Math.Ceiling((thisArea.Amount / 8.0));
                                    IntData[i].dByte = new byte[tAmount];

                                    if (!thisArea.Write)
                                    {
                                        //Add Reader variable areas.
                                        Reader.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }
                                    else
                                    {
                                        //Add Writer variable areas.
                                        Writer.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }

                                    break;

                                case DriverConfig.DatType.Byte:
                                    IntData[i].dByte = new byte[thisArea.Amount];

                                    if (!thisArea.Write)
                                    {
                                        //Add Reader variable areas.
                                        Reader.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, thisArea.Amount, ref IntData[i].dByte);
                                    }
                                    else
                                    {
                                        //Add Writer variable areas.
                                        Writer.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, thisArea.Amount, ref IntData[i].dByte);
                                    }

                                    break;

                                case DriverConfig.DatType.Word:
                                    tAmount          = (int)(thisArea.Amount * 2.0);
                                    IntData[i].dByte = new byte[tAmount];
                                    IntData[i].dWord = new UInt16[thisArea.Amount];

                                    if (!thisArea.Write)
                                    {
                                        //Add Reader variable areas.
                                        Reader.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }
                                    else
                                    {
                                        //Add Writer variable areas.
                                        Writer.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }

                                    break;

                                case DriverConfig.DatType.DWord:
                                    tAmount           = (int)(thisArea.Amount * 4.0);
                                    IntData[i].dByte  = new byte[tAmount];
                                    IntData[i].dDWord = new UInt32[thisArea.Amount];

                                    if (!thisArea.Write)
                                    {
                                        //Add Reader variable areas.
                                        Reader.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }
                                    else
                                    {
                                        //Add Writer variable areas.
                                        Writer.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }

                                    break;

                                case DriverConfig.DatType.Real:
                                    tAmount          = (int)(thisArea.Amount * 4.0);
                                    IntData[i].dByte = new byte[tAmount];
                                    IntData[i].dReal = new float[thisArea.Amount];

                                    if (!thisArea.Write)
                                    {
                                        //Add Reader variable areas.
                                        Reader.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }
                                    else
                                    {
                                        //Add Writer variable areas.
                                        Writer.Add(S7Client.S7AreaDB, datSize, thisArea.DBnumber,
                                                   SAddress, tAmount, ref IntData[i].dByte);
                                    }

                                    break;

                                default:
                                    retVal = false;
                                    Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config.");
                                    break;
                                }
                                j++;
                            } // Area Enable
                        }     // For Data Areas

                        //check there is enabled data areas.
                        if (j == 0)
                        {
                            retVal = false;
                        }
                    }
                    catch (Exception e)
                    {
                        retVal = false;
                        Status.NewStat(StatType.Bad, e.Message);
                    }
                } // IF not isInitialized
            }
            if (retVal)
            {
                Status.NewStat(StatType.Good);
            }
            else
            {
                Status.NewStat(StatType.Bad, "Initialization Failed.");
            }

            isInitialized = retVal;
        } // END Function Initialized
Ejemplo n.º 17
0
        public BllResult Writes(List <EquipmentProp> equipmentProps)
        {
            if (equipmentProps == null || equipmentProps.Count() == 0)
            {
                return(BllResultFactory.Error($"未传递属性"));
            }
            var ips = equipmentProps.Select(t => t.Equipment).Select(t => t.IP).Distinct().ToList();

            foreach (var item in ips)
            {
                var temp = S7PLCHelpers.FirstOrDefault(t => t.PLCIP == item);
                //确定属性中对应的PLC是否存在连接
                if (!temp.S7Client.Connected)
                {
                    return(BllResultFactory.Error($"存在IP为{item}的PLC未连接"));
                }
            }

            try
            {
                foreach (var item in ips)
                {
                    var        props      = equipmentProps.Where(t => t.Equipment.IP == item).ToList();
                    var        client     = S7PLCHelpers.FirstOrDefault(t => t.PLCIP == item).S7Client;
                    S7MultiVar s7MultiVar = new S7MultiVar(client);
                    int        count      = 20;
                    int        i          = 0;
                    while (true)
                    {
                        var tempProps = props.Skip(i).Take(count);
                        i += count;
                        if (tempProps.Count() == 0)
                        {
                            break;
                        }
                        //添加dataitem
                        foreach (var prop in tempProps)
                        {
                            var result = S7PLCHelper.AddressAnalyze(prop.Address);
                            if (!result.Success)
                            {
                                return(BllResultFactory.Error($"地址解析错误,属性明细Id:{prop.Id},详情:{result.Msg}"));
                            }
                            var tran = result.Data;
                            if (!Enum.TryParse <PLCDataType>(prop.EquipmentTypeTemplate.DataType, out PLCDataType dataType))
                            {
                                return(BllResultFactory.Error($"未识别的数据类型{prop.EquipmentTypeTemplate.DataType}"));
                            }
                            var temp = S7PLCHelper.TransferStringToBuffer(dataType, prop.Value.PadRight(20, ' '));
                            if (!temp.Success)
                            {
                                return(BllResultFactory.Error($"转换数据出错:{temp.Msg}"));
                            }
                            var tempBytes = temp.Data;
                            if (s7MultiVar.Add(tran.Area, tran.DataType, tran.DataNumber, tran.DataOffset, tran.DataAmount, ref tempBytes) == false)
                            {
                                return(BllResultFactory.Error("添加地址失败"));
                            }
                        }
                        GetLock(item);
                        int flag = s7MultiVar.Write();
                        ResetLock(item);
                        if (flag != 0)
                        {
                            return(BllResultFactory.Error($"写入错误:{client.ErrorText(flag)}"));
                        }
                        var tempp = s7MultiVar.Results.ToList().Where(t => t != 0).ToList();
                        if (tempp.Count > 0)
                        {
                            return(BllResultFactory.Error($"存在写入错误:{client.ErrorText(tempp[0])}"));
                        }
                        s7MultiVar.Clear();
                    }
                    ;
                }
            }
            catch (Exception ex)
            {
                return(BllResultFactory.Error($"写入出现异常:{ex.ToString() }"));
            }

            return(BllResultFactory.Sucess());
        }
Ejemplo n.º 18
0
        public BllResult Reads(List <EquipmentProp> equipmentProps)
        {
            if (equipmentProps == null || equipmentProps.Count() == 0)
            {
                return(BllResultFactory.Error($"未传递属性"));
            }
            //选取设备类
            var ips = equipmentProps.Select(t => t.Equipment).Select(t => t.IP).Distinct().ToList();

            //设备类是否对应PLC配置IP
            foreach (var item in ips)
            {
                var temp = S7PLCHelpers.FirstOrDefault(t => t.PLCIP == item);
                //确定属性中对应的PLC是否存在连接
                if (temp.S7Client == null || !temp.S7Client.Connected)
                {
                    return(BllResultFactory.Error($"存在IP为{item}的PLC未连接"));
                }
            }

            try
            {
                foreach (var item in ips)
                {
                    //缓存
                    List <byte[]> list       = new List <byte[]>();
                    var           props      = equipmentProps.Where(t => t.Equipment.IP == item).ToList();
                    var           client     = S7PLCHelpers.FirstOrDefault(t => t.PLCIP == item).S7Client;
                    S7MultiVar    s7MultiVar = new S7MultiVar(client);
                    int           count      = 10;
                    int           i          = 0;
                    while (true)
                    {
                        var tempProps = props.Skip(i).Take(count);
                        i += count;
                        if (tempProps.Count() == 0)
                        {
                            break;
                        }
                        //添加dataitem
                        foreach (var prop in tempProps)
                        {
                            var result = S7PLCHelper.AddressAnalyze(prop.Address);
                            if (!result.Success)
                            {
                                return(BllResultFactory.Error($"地址解析错误,属性明细Id:{prop.Id},详情:{result.Msg}"));
                            }
                            var tran = result.Data;
                            var temp = new byte[256];
                            if (s7MultiVar.Add(tran.Area, tran.DataType, tran.DataNumber, tran.DataOffset, tran.DataAmount, ref temp) == false)
                            {
                                return(BllResultFactory.Error("添加地址失败"));
                            }
                            list.Add(temp);
                        }
                        GetLock(item);
                        int flag = s7MultiVar.Read();
                        ResetLock(item);
                        if (flag != 0)
                        {
                            return(BllResultFactory.Error($"读取错误:{client.ErrorText(flag)}"));
                        }
                        var tempp = s7MultiVar.Results.ToList().Where(t => t != 0).ToList();
                        if (tempp.Count > 0)
                        {
                            return(BllResultFactory.Error($"存在读取错误:{client.ErrorText(tempp[0])}"));
                        }
                        s7MultiVar.Clear();
                    }
                    ;

                    //转换读取后的值
                    Console.WriteLine(DateTime.Now);
                    for (int g = 0; g < props.Count; g++)
                    {
                        if (!Enum.TryParse <PLCDataType>(props[g].EquipmentTypeTemplate.DataType, out PLCDataType dataType))
                        {
                            return(BllResultFactory.Error($"未识别的数据类型{props[g].EquipmentTypeTemplate.DataType}"));
                        }
                        var result = S7PLCHelper.TransferBufferToString(dataType, list[g]);
                        if (result.Success)
                        {
                            props[g].Value = result.Data;
                            Console.WriteLine(props[g].EquipmentTypeTemplateCode + ":" + props[g].Value);
                        }
                        else
                        {
                            return(BllResultFactory.Error($"读取数据出错:{result.Msg}"));
                        }
                    }
                    s7MultiVar.Clear();
                    Console.WriteLine("");
                }
            }
            catch (Exception ex)
            {
                return(BllResultFactory.Error($"读取出现异常:" + ex.ToString()));
            }

            return(BllResultFactory.Sucess());
        }
        public void RefreshValues()
        {
            lock (_locker)

            //{
            //    var s7MultiVar = new S7MultiVar(_client);
            //    byte[] buffer189 = new byte[20];
            //    s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 189, 0, 20, ref buffer189);
            //    int result189 = s7MultiVar.Read();
            //    if (result189 == 0)
            //    {
            //        INFSTSPDP = Math.Round(S7.GetRealAt(buffer189, 0), 1);
            //        a = INFSTSPDP.ToString();
            //        IQFSTSPDP = Math.Round(S7.GetRealAt(buffer189, 4), 1);
            //        GLZSTSPDP = Math.Round(S7.GetRealAt(buffer189, 8), 1);
            //        HDSTSPDP = Math.Round(S7.GetRealAt(buffer189, 12), 1);
            //        RFSTSPDP = Math.Round(S7.GetRealAt(buffer189, 16), 1);
            //    }
            //    else
            //    {
            //        Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t Read error: " + _client.ErrorText(result189));
            //    }
            //}

            // READ: CONVEYORS SPEED TIME
            {
                var    s7MultiVar = new S7MultiVar(_client);
                byte[] buffer88   = new byte[20];
                s7MultiVar.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 88, 0, 20, ref buffer88);
                int result88 = s7MultiVar.Read();
                if (result88 == 0)
                {
                    INFSP = Math.Round(S7.GetRealAt(buffer88, 0), 1);
                    IQFSP = Math.Round(S7.GetRealAt(buffer88, 4), 1);
                    GLZSP = Math.Round(S7.GetRealAt(buffer88, 8), 1);
                    HDSP  = Math.Round(S7.GetRealAt(buffer88, 12), 1);
                    RFSP  = Math.Round(S7.GetRealAt(buffer88, 16), 1);
                }
                else
                {
                    Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t Read error: " + _client.ErrorText(result88));
                }
            }

            // READ: TEMPERATURE

            {
                var    s7MultiVar2 = new S7MultiVar(_client);
                byte[] buffer186   = new byte[19];
                s7MultiVar2.Add(S7Consts.S7AreaDB, S7Consts.S7WLByte, 186, 0, 19, ref buffer186);
                int result186 = s7MultiVar2.Read();
                if (result186 == 0)
                {
                    IQFTEMP = Math.Round(S7.GetRealAt(buffer186, 0), 1);
                    CLWTEMP = Math.Round(S7.GetRealAt(buffer186, 4), 1);
                    RFTEMP  = Math.Round(S7.GetRealAt(buffer186, 8), 1);
                    CTBTEMP = Math.Round(S7.GetRealAt(buffer186, 12), 1);

                    // READ DEVICES STATE
                    Blower1 = S7.GetBitAt(buffer186, 16, 0);
                    Blower2 = S7.GetBitAt(buffer186, 16, 1);
                    Blower3 = S7.GetBitAt(buffer186, 16, 2);
                    Blower4 = S7.GetBitAt(buffer186, 16, 3);
                    Blower5 = S7.GetBitAt(buffer186, 16, 4);
                    Blower6 = S7.GetBitAt(buffer186, 16, 5);
                    Blower7 = S7.GetBitAt(buffer186, 16, 6);
                    Blower8 = S7.GetBitAt(buffer186, 16, 7);
                    Blower9 = S7.GetBitAt(buffer186, 17, 0);

                    FlashingL = S7.GetBitAt(buffer186, 17, 1);

                    IQF_LSV   = S7.GetBitAt(buffer186, 17, 2);
                    IQF_BDV   = S7.GetBitAt(buffer186, 17, 3);
                    IQF_AP    = S7.GetBitAt(buffer186, 17, 4);
                    IQF_CDV   = S7.GetBitAt(buffer186, 17, 5);
                    IQF_BD_WP = S7.GetBitAt(buffer186, 17, 6);
                    IQF_CD_WP = S7.GetBitAt(buffer186, 17, 7);

                    RF_LSV   = S7.GetBitAt(buffer186, 18, 0);
                    RF_BDV   = S7.GetBitAt(buffer186, 18, 1);
                    RF_AP    = S7.GetBitAt(buffer186, 18, 2);
                    RF_CDV   = S7.GetBitAt(buffer186, 18, 3);
                    RF_BD_WP = S7.GetBitAt(buffer186, 18, 4);
                    RF_CD_WP = S7.GetBitAt(buffer186, 18, 5);
                }
                else
                {
                    Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t Read error: " + _client.ErrorText(result186));
                }
            }
        }