Пример #1
0
 public void Update(byte[] Src, int Pos)
 {
     MaxPduLength   = S7.GetShortAt(Src, 2);
     MaxConnections = S7.GetShortAt(Src, 4);
     MaxMpiRate     = S7.GetDIntAt(Src, 6);
     MaxBusRate     = S7.GetDIntAt(Src, 10);
 }
Пример #2
0
        public static void StateMotor(int numDB)
        {
            // Initialisation
            var res = -1;                    // Résultat de la fonction

            byte[] Buffer    = new byte[2];  // Buffer 2 bytes
            byte[] BufferBis = new byte[55]; // Buffer 10 bytes

            if (Main._statusConnection)
            {
                res = Main.Client.DBRead(numDB, 80, 2, Buffer);
            }

            BitArray arBits = new BitArray(Buffer); // Convert buffer bytes to array of bits

            for (int i = 0; i < 15; i++)
            {
                Main._arStateMotor.Add(arBits.Get(i)); // Fill the array
            }
            if (Main._statusConnection)
            {
                res = Main.Client.DBRead(numDB, 56, 55, BufferBis);
            }

            Main._dspdMotor  = S7.GetRealAt(BufferBis, 0);
            Main._dintMotor  = S7.GetIntAt(BufferBis, 6) / 10;
            Main._dspdFMotor = S7.GetDIntAt(BufferBis, 48) / 100;
        }
Пример #3
0
        public static double ReadWeldingCurrent(S7Client client)
        {
            result = client.DBRead(1024, 0, 8, ReadBuffer);
            double dbCurrent = S7.GetDIntAt(ReadBuffer, 4);

            return(dbCurrent);
        }
Пример #4
0
 public void Parse(byte[] buffer, int start)
 {
     plcDateTime         = S7.GetDateTimeAt(buffer, start); start = start + 8;
     logEntryNumber      = S7.GetDIntAt(buffer, start);  start = start + 4;
     SRMNumber           = S7.GetIntAt(buffer, start);        start = start + 2;
     logEntryType        = S7.GetStringAt(buffer, start);        start = start + 52;
     logEntryDescription = S7.GetStringAt(buffer, start); start = start + 202;
     functionName        = S7.GetStringAt(buffer, start);       start = start + 52;
     operationMode       = S7.GetStringAt(buffer, start);       start = start + 52;
     faultOrWarningState = (FaultOrWarningState)S7.GetIntAt(buffer, start);    start = start + 2;
     XPosition_mm        = S7.GetDIntAt(buffer, start); start = start + 4;
     YPosition_mm        = S7.GetDIntAt(buffer, start); start = start + 4;
     Z1Position_mm       = S7.GetIntAt(buffer, start); start = start + 2;
     Z2Position_mm       = S7.GetIntAt(buffer, start); start = start + 2;
     Z3Position_mm       = S7.GetIntAt(buffer, start); start = start + 2;
     Z4Position_mm       = S7.GetIntAt(buffer, start); start = start + 2;
     XTarget_mm          = S7.GetDIntAt(buffer, start); start = start + 4;
     YTarget_mm          = S7.GetDIntAt(buffer, start); start = start + 4;
     Z1Target_mm         = S7.GetIntAt(buffer, start); start = start + 2;
     Z2Target_mm         = S7.GetIntAt(buffer, start); start = start + 2;
     Z3Target_mm         = S7.GetIntAt(buffer, start); start = start + 2;
     Z4Target_mm         = S7.GetIntAt(buffer, start); start = start + 2;
     XSpeed_mmps         = S7.GetIntAt(buffer, start); start = start + 2;
     YSpeed_mmps         = S7.GetIntAt(buffer, start); start = start + 2;
     Z1Speed_mmps        = S7.GetIntAt(buffer, start); start = start + 2;
     Z2Speed_mmps        = S7.GetIntAt(buffer, start); start = start + 2;
     Z3Speed_mmps        = S7.GetIntAt(buffer, start); start = start + 2;
     Z4Speed_mmps        = S7.GetIntAt(buffer, start); start = start + 2;
 }
Пример #5
0
        private static double[] ReadCountersProduction(int nbDays)
        {
            //-------------- Read DB98
            var res = -1;                        // Result of the function

            byte[]   DB98Buffer = new byte[100]; // Buffer 100 bytes
            double[] temp = new double[24];      // Array one day
            int      Start, Size;                // Parameters of the function
            int      hour = DateTime.Now.Hour;

            //hour = hour - 1;

            if (nbDays == 0)
            {
                Start = 18;       // Start at DB98.DBD18
                Size  = hour * 4; // Read from current hour to the begin of the day
            }
            else
            {
                if (nbDays == 1)
                {
                    Start = 18 + (hour * 4);
                }
                else
                {
                    Start = 18 + (hour * 4) + ((nbDays - 1) * 24 * 4);
                }

                Size = 24 * 4; // Read one day
            }

            if (statusCon)
            {
                res = cpu.DBRead(98, Start, Size, DB98Buffer); // Read DB98
            }
            if (!(res == 0))
            {
                return(temp); // Break the function
            }
            if ((nbDays == 0) & (res == 0))
            {
                int j = hour - 1;
                for (int i = 0; i < hour; i++)
                {
                    temp[j] = S7.GetDIntAt(DB98Buffer, i * 4); // Fill the array
                    j       = j - 1;
                }
            }
            if ((nbDays > 0) & (res == 0))
            {
                int j = 23;
                for (int i = 0; i < 23; i++)
                {
                    temp[j] = S7.GetDIntAt(DB98Buffer, i * 4); // Fill the array
                    j       = j - 1;
                }
            }

            return(temp); // Return values
        }
Пример #6
0
        private void BtnUpdateMonitor_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.m_InfoList.Count < 0)
                {
                    throw new Exception(@"不存在正在监视的变量");
                }

                for (var index = 0; index < this.m_InfoList.Count; index++)
                {
                    var    block        = this.m_BlockDict[this.m_InfoList[index].BlockName];
                    var    offsetByte   = this.m_InfoList[index].OffsetByte;
                    var    offsetBit    = this.m_InfoList[index].OffsetBit;
                    var    stringLength = this.m_InfoList[index].StringLength;
                    var    dataType     = this.m_InfoList[index].DataType;
                    string strValue;
                    switch (dataType)
                    {
                    case DataType.Bit: strValue = S7.GetBitAt(block, offsetByte, offsetBit).ToString(); break;

                    case DataType.Byte: strValue = S7.GetUSIntAt(block, offsetByte).ToString(); break;

                    case DataType.Ushort: strValue = S7.GetUIntAt(block, offsetByte).ToString(); break;

                    case DataType.Uint: strValue = S7.GetUDIntAt(block, offsetByte).ToString(); break;

                    case DataType.Ulong: strValue = S7.GetULIntAt(block, offsetByte).ToString(); break;

                    case DataType.Sbyte: strValue = S7.GetSIntAt(block, offsetByte).ToString(); break;

                    case DataType.Short: strValue = S7.GetIntAt(block, offsetByte).ToString(); break;

                    case DataType.Int: strValue = S7.GetDIntAt(block, offsetByte).ToString(); break;

                    case DataType.Long: strValue = S7.GetLIntAt(block, offsetByte).ToString(); break;

                    case DataType.Float: strValue = S7.GetRealAt(block, offsetByte).ToString(CultureInfo.InvariantCulture); break;

                    case DataType.Double: strValue = S7.GetLRealAt(block, offsetByte).ToString(CultureInfo.InvariantCulture); break;

                    case DataType.String:
                        var byteArr = new byte[stringLength];
                        Array.Copy(block, offsetByte, byteArr, 0, stringLength);
                        strValue = System.Text.Encoding.ASCII.GetString(byteArr);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    this.lvMonitor.Items[index].SubItems[2].Text = strValue;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #7
0
        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            int Result;

            //1605 = 170LH
            //1601 = 160lLH
            //1617 = 200LH
            //size = 1400
            Result = Client.DBRead(Convert.ToInt32(TxtIP_Copy.Text), 0, 1500, Buffer);

            MesClass Mesdata = new MesClass();

            if (Result == 0)
            {
                //pos 700
                int    DInt   = S7.GetDIntAt(Buffer, 700);
                string inter  = S7.GetStringAt(Buffer, 726);
                string serial = S7.GetStringAt(Buffer, 764);
                string sss    = serial.Trim();
                string ssss   = "";
                string iii    = inter.Trim();

                if (sss == "")
                {
                    ssss = "0";
                }
                else
                {
                    sss = sss.Substring(0, 2);
                    iii = iii.Substring(0, 6);

                    //search the db - 1 or 2 characters
                    if (sss.Contains(";"))
                    {
                        sss = sss.Substring(0, 1);
                    }
                    ssss = Mesdata.Get_Part(sss);

                    LblText.Content      = System.Convert.ToString(DInt);
                    LblText_Copy.Content = iii;

                    listBox1.Items.Add(System.Convert.ToString(DInt) + " -- " + ssss + " (" + sss + ") -- " + iii + " --- " + DateTime.Now.ToString("HH:mm:ss"));
                    listBox1.Items.MoveCurrentToLast();
                }


                listBox1.SelectedItem = listBox1.Items.CurrentItem;
                listBox1.ScrollIntoView(listBox1.Items.CurrentItem);
            }
            else
            {
                MessageBox.Show("failed to read");
            }
        }
Пример #8
0
        private bool ReadValue()
        {
            var client = _connection?.PlcClient;

            if (client == null)
            {
                return(false);
            }

            var buffer = new byte[Math.Max(64, _info.ByteCount + 2)];
            var result = client.DBRead(_info.DbNumber, _info.Offset, _info.ByteCount, buffer);

            if (result != 0)
            {
                TronTrace.TraceError($"PlcItem.DBRead({_info.DbNumber}, {_info.Offset}) failed - {result} {PlcResult.GetResultText(result)}");
                return(false);
            }

            switch (_info.PlcDataType)
            {
            case PlcDataTypes.X:
                _value = S7.GetBitAt(buffer, 0, _info.Bit) ? 1 : 0;
                break;

            case PlcDataTypes.B:
                _value = S7.GetByteAt(buffer, 0);
                break;

            case PlcDataTypes.INT:
                _value = S7.GetIntAt(buffer, 0);
                break;

            case PlcDataTypes.DINT:
                _value = S7.GetDIntAt(buffer, 0);
                break;

            case PlcDataTypes.DT:
                _value = S7.GetDateTimeAt(buffer, 0);
                break;

            case PlcDataTypes.STRING:
                _value = S7.GetStringAt(buffer, 0);
                break;
            }

            if (!_value.Equals(_oldValue))
            {
                _oldValue = _value;
                ValueChanged?.Invoke(this);
            }
            return(true);
        }
Пример #9
0
        private static void Reader_ReadHandler(object sender, ReadEventArgs e)
        {
            Task.Run(() =>
            {
                if (e.Result == 0 || e.Result == 5)
                {
                    var CXNCKD = S7.GetIntAt(e.Data, 42);
                    Console.WriteLine(string.Format("一号线-车辆车厢内侧宽度:{0}", CXNCKD));

                    var CXNCCD = S7.GetIntAt(e.Data, 40);
                    Console.WriteLine(string.Format("一号线-车辆车厢内侧长度:{0}", CXNCCD));

                    var CKGD = S7.GetIntAt(e.Data, 6);
                    Console.WriteLine(string.Format("一号线-车框高度:{0}", CKGD));

                    var SDZCBS = S7.GetIntAt(e.Data, 36);
                    Console.WriteLine(string.Format("一号线-设定装车包数:{0}", SDZCBS));

                    var JHZQCS = S7.GetIntAt(e.Data, 34);
                    Console.WriteLine(string.Format("一号线-计划抓取次数:{0}", JHZQCS));

                    var DQZCSKZL = S7.GetIntAt(e.Data, 176);
                    Console.WriteLine(string.Format("一号线-当前装车刷卡重量:{0}", DQZCSKZL));

                    var ZZCS = S7.GetDIntAt(e.Data, 138);
                    Console.WriteLine(string.Format("一号线-总装车数:{0}", ZZCS));

                    var DTZCS = S7.GetIntAt(e.Data, 142);
                    Console.WriteLine(string.Format("一号线-当天装车数:{0}", DTZCS));

                    var ZZCZL = S7.GetRealAt(e.Data, 158);
                    Console.WriteLine(string.Format("一号线-总装车重量:{0}", ZZCZL));

                    var DTZCZL = S7.GetRealAt(e.Data, 162);
                    Console.WriteLine(string.Format("一号线-当天装车重量:{0}", DTZCZL));

                    var JCSJHG = S7.GetBitAt(e.Data, 70, 2);
                    Console.WriteLine(string.Format("一号线-检测数据合格:{0}", JCSJHG));

                    var WMBXZHG = S7.GetBitAt(e.Data, 70, 3);
                    Console.WriteLine(string.Format("一号线-尾门板X值合格:{0}", WMBXZHG));

                    var DQZCZL = S7.GetDIntAt(e.Data, 0);
                    Console.WriteLine(string.Format("一号线-当前装车重量:{0}", DQZCZL));

                    var CPH = S7.GetStringAt(e.Data, 180, Encoding.GetEncoding("GB2312"));
                    Console.WriteLine(string.Format("一号线-车牌号:{0}", CPH));
                }
                e.Dispose();
                e = null;
            });
        }
Пример #10
0
        internal static object GetS7Value(Tag tagItem, byte[] buffer)
        {
            object returnValue;

            if (tagItem.DataType == "Bit")
            {
                returnValue = S7.GetBitAt(buffer, tagItem.Position, 0);
            }
            else if (tagItem.DataType == "Word")
            {
                returnValue = S7.GetWordAt(buffer, 0);
            }
            else if (tagItem.DataType == "Short")
            {
                returnValue = S7.GetShortAt(buffer, 0);
            }
            else if (tagItem.DataType == "DWord")
            {
                returnValue = S7.GetDWordAt(buffer, 0);
            }
            else if (tagItem.DataType == "DInt")
            {
                returnValue = S7.GetDIntAt(buffer, 0);
            }
            else if (tagItem.DataType == "Float")
            {
                returnValue = S7.GetFloatAt(buffer, 0);
            }
            else if (tagItem.DataType == "String")
            {
                returnValue = S7.GetStringAt(buffer, 0, buffer.Length);
            }
            else if (tagItem.DataType == "PrintableString")
            {
                returnValue = S7.GetPrintableStringAt(buffer, 0, buffer.Length);
            }
            else if (tagItem.DataType == "Date")
            {
                returnValue = S7.GetDateAt(buffer, 0);
            }
            else
            {
                returnValue = S7.GetStringAt(buffer, 0, buffer.Length);
            }
            return(returnValue);
        }
Пример #11
0
        /// <summary>
        /// extract value from raw buffer
        /// </summary>
        /// <param name="buffer"> buffer length must be greater than Offset.ByteOffset+4, else do nothing </param>
        public void GetValueFromGroupBuffer(byte[] buffer)
        {
            if (buffer.Length < Offset.ByteOffset + 4)
            {
                return;
            }
            switch (VType)
            {
            case varType.BOOL:
                Value = S7.GetBitAt(buffer, Offset.ByteOffset, Offset.BitOffset);
                break;

            case varType.BYTE:
                Value = S7.GetByteAt(buffer, Offset.ByteOffset);
                break;

            case varType.WORD:
                Value = S7.GetWordAt(buffer, Offset.ByteOffset);
                break;

            case varType.DWORD:
                Value = S7.GetDWordAt(buffer, Offset.ByteOffset);
                break;

            case varType.INT:
                Value = S7.GetIntAt(buffer, Offset.ByteOffset);
                break;

            case varType.DINT:
                Value = S7.GetDIntAt(buffer, Offset.ByteOffset);
                break;

            case varType.REAL:
                Value = S7.GetRealAt(buffer, Offset.ByteOffset);
                break;

            // Added String Read
            case varType.STRING:
                Value = S7.GetStringAt(buffer, Offset.ByteOffset);
                break;
            }
        }
Пример #12
0
        public string GetDecS(byte[] buffer)
        {
            string i = "[Error]";

            switch (buffer.Length)
            {
            case 1:
                i = S7.GetSIntAt(buffer, 0).ToString();
                break;

            case 2:
                i = S7.GetIntAt(buffer, 0).ToString();
                break;

            case 4:
                i = S7.GetDIntAt(buffer, 0).ToString();
                break;
            }

            return(i);
        }
Пример #13
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();
        }
Пример #14
0
        private void FieldBtn_Click(object sender, EventArgs e)
        {
/*
 *        0 Byte    8 Bit Word                     (All)
 *        1 Word   16 Bit Word                     (All)
 *        2 DWord  32 Bit Word                     (All)
 *        3 LWord  64 Bit Word                     (S71500)
 *        4 USint   8 Bit Unsigned Integer         (S71200/1500)
 *        5 UInt   16 Bit Unsigned Integer         (S71200/1500)
 *        6 UDInt  32 Bit Unsigned Integer         (S71200/1500)
 *        7 ULint  64 Bit Unsigned Integer         (S71500)
 *        8 Sint    8 Bit Signed Integer           (S71200/1500)
 *        9 Int    16 Bit Signed Integer           (All)
 *       10 DInt   32 Bit Signed Integer           (S71200/1500)
 *       11 LInt   64 Bit Signed Integer           (S71500)
 *       12 Real   32 Bit Floating point           (All)
 *       13 LReal  64 Bit Floating point           (S71200/1500)
 *       14 Time   32 Bit Time elapsed ms          (All)
 *       15 LTime  64 Bit Time Elapsed ns          (S71500)
 *       16 Date   16 Bit days from 1990/1/1       (All)
 *       17 TOD    32 Bit ms elapsed from midnight (All)
 *       18 DT      8 Byte Date and Time           (All)
 *       19 LTOD   64 Bit time of day (ns)         (S71500)
 *       20 DTL    12 Byte Date and Time Long      (S71200/1500)
 *       21 LDT    64 Bit ns elapsed from 1970/1/1 (S71500)
 */
            int Pos = System.Convert.ToInt32(TxtOffset.Text);

            switch (CBType.SelectedIndex)
            {
            case 0:
            {
                TxtValue.Text = "16#" + System.Convert.ToString(Buffer[Pos], 16).ToUpper();
                break;
            }

            case 1:
            {
                UInt16 Word = S7.GetWordAt(Buffer, Pos);
                TxtValue.Text = "16#" + System.Convert.ToString(Word, 16).ToUpper();
                break;
            }

            case 2:
            {
                UInt32 DWord = S7.GetDWordAt(Buffer, Pos);
                TxtValue.Text = "16#" + System.Convert.ToString(DWord, 16).ToUpper();
                break;
            }

            case 3:
            {
                UInt64 LWord = S7.GetLWordAt(Buffer, Pos);
                TxtValue.Text = "16#" + System.Convert.ToString((Int64)LWord, 16).ToUpper();         // <-- Convert.ToString does not handle UInt64
                break;
            }

            case 4:
            {
                UInt16 USInt = S7.GetUSIntAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(USInt);
                break;
            }

            case 5:
            {
                UInt16 UInt = S7.GetUIntAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(UInt);
                break;
            }

            case 6:
            {
                UInt32 UDInt = S7.GetDWordAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(UDInt);
                break;
            }

            case 7:
            {
                UInt64 ULInt = S7.GetLWordAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(ULInt);
                break;
            }

            case 8:
            {
                int SInt = S7.GetSIntAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(SInt);
                break;
            }

            case 9:
            {
                int S7Int = S7.GetIntAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(S7Int);
                break;
            }

            case 10:
            {
                int DInt = S7.GetDIntAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(DInt);
                break;
            }

            case 11:
            {
                Int64 LInt = S7.GetLIntAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(LInt);
                break;
            }

            case 12:
            {
                Single S7Real = S7.GetRealAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(S7Real);
                break;
            }

            case 13:
            {
                Double S7LReal = S7.GetLRealAt(Buffer, Pos);
                TxtValue.Text = System.Convert.ToString(S7LReal);
                break;
            }

            case 14:
            {
                Int32 TimeElapsed = S7.GetDIntAt(Buffer, Pos);
                // TIME type is a 32 signed number of ms elapsed
                // Can be added to a DateTime or used as Value.
                TxtValue.Text = "T#" + System.Convert.ToString(TimeElapsed) + "MS";
                break;
            }

            case 15:
            {
                Int64 TimeElapsed = S7.GetLIntAt(Buffer, Pos);
                // LTIME type is a 64 signed number of ns elapsed
                // Can be added (after a conversion) to a DateTime or used as Value.
                TxtValue.Text = "LT#" + System.Convert.ToString(TimeElapsed) + "NS";
                break;
            }

            case 16:
            {
                DateTime DATE = S7.GetDateAt(Buffer, Pos);
                TxtValue.Text = DATE.ToString("D#yyyy-MM-dd");
                break;
            }

            case 17:
            {
                DateTime TOD = S7.GetTODAt(Buffer, Pos);
                TxtValue.Text = TOD.ToString("TOD#HH:mm:ss.fff");
                break;
            }

            case 18:
            {
                DateTime DT = S7.GetDateTimeAt(Buffer, Pos);
                TxtValue.Text = DT.ToString("DT#yyyy-MM-dd-HH:mm:ss.fff");
                break;
            }

            case 19:
            {
                DateTime LTOD = S7.GetLTODAt(Buffer, Pos);
                TxtValue.Text = LTOD.ToString("LTOD#HH:mm:ss.fffffff");
                break;
            }

            case 20:
            {
                DateTime DTL = S7.GetDTLAt(Buffer, Pos);
                TxtValue.Text = DTL.ToString("DTL#yyyy-MM-dd-HH:mm:ss.fffffff");
                break;
            }

            case 21:
            {
                DateTime LDT = S7.GetLDTAt(Buffer, Pos);
                TxtValue.Text = LDT.ToString("LDT#yyyy-MM-dd-HH:mm:ss.fffffff");
                break;
            }
            }
        }
Пример #15
0
        private void tmrLetturaDatiPLC_Tick(object sender, EventArgs e)
        {
            try
            {
                //lettura dei dati dal PLC
                this.result = this.Client.DBRead(2, 0, this.db2Buffer.Length, this.db2Buffer);

                string codiceCommessa = S7.GetStringAt(this.db1Buffer, 0);
                //string prodotto = S7.GetStringAt(this.db1Buffer, 52);
                int    pezziProdotti             = S7.GetDIntAt(this.db2Buffer, 104);
                int    pezziScartatiScaricoPieno = S7.GetDIntAt(this.db2Buffer, 108);
                int    pezziScartatiDifettosi    = S7.GetDIntAt(this.db2Buffer, 112);
                int    pezziScartatiTotali       = pezziScartatiDifettosi + pezziScartatiScaricoPieno;
                int    statoMacchina             = S7.GetUSIntAt(this.db2Buffer, 116);
                int    velocitàMacchina          = S7.GetDIntAt(this.db2Buffer, 118);
                string newMessaggioOperatore     = S7.GetStringAt(this.db2Buffer, 130);
                allarmi = S7.GetUSIntAt(this.db2Buffer, 232);

                CSerialDeserial.WriteFile(this.db2);

                //visualizza gli allarmi
                setVisualizzazioneAllarmi(allarmi);

                //se è presente un allarme e non è mai stata mostrato l'alert, viene mostrato
                if (allarmi != 0 && mostraAlertAllarme)
                {
                    Alert("ALLARME!", AlertDLL.Alert.enmType.Error);
                    mostraAlertAllarme = false;
                }
                //se non ci sono allarmi, resetto la booleana
                if (allarmi == 0)
                {
                    mostraAlertAllarme = true;
                }

                string strStatoMacchina = calcoloStatoMacchina(statoMacchina);
                txtStatoMacchina.Text = strStatoMacchina;

                //se è presente una commessa in esecuzione sul plc, imposto le variabili opportune per la visualizzazione
                if (codiceCommessa != "")
                {
                    if (txtPezziProdotti.Text != ("" + pezziProdotti) || txtPezziScartati.Text != ("" + pezziScartatiTotali))
                    {
                        setTempoRimanenteEProgressBar(velocitàMacchina, pezziProdotti);
                    }

                    txtPezziProdotti.Text = "" + pezziProdotti;
                    txtPezziScartati.Text = "" + pezziScartatiTotali;
                    txtVelocita.Text      = "" + velocitàMacchina;
                }
                else
                {
                    setNullTextBoxes();
                }

                //se il messaggio dell'operatore è diverso da l'ultimo che è arrivatom viene attivata la notifica
                if (newMessaggioOperatore != messaggioOperatore)
                {
                    messaggioOperatore = newMessaggioOperatore;
                    mostrareMessaggio  = true;
                    NotificaMessaggioDaOperatore();
                }

                //set delle immagini per la notifica su pagina Gestione Commesse
                if (mostrareMessaggio)
                {
                    btnDialogoPcPlc.BackgroundImage = PLC_Manager.Properties.Resources.icona_NotficaPresenza;
                }
                else
                {
                    btnDialogoPcPlc.BackgroundImage = PLC_Manager.Properties.Resources.icona_nessunaNotifica;
                }

                //concusione della commessa
                if (strStatoMacchina == "CONCLUSO")
                {
                    DBManager.updateStatoCommessa(codiceCommessa, "completata");
                    commesse.completaCommessa(codiceCommessa);

                    Alert("Commessa conclusa", AlertDLL.Alert.enmType.Info);

                    Thread.Sleep(2000); //il codice viene bloccato per 2 secondi, per lasciare il tempo al servizio di leggere i dati

                    eliminaEsecuzioneCommessaSulPLC();
                    MandaInEsecuzioneCommessaSuccessiva();
                    AggiornaDataGridViewCommesse();
                }
            }
            catch (Exception)
            {
                Alert("Errore non gestito", AlertDLL.Alert.enmType.Error);
            }
        }
Пример #16
0
        private void BtnRead_Click(object sender, EventArgs e)
        {
            try
            {
                #region 数据类型
                if (this.cboxDataType.SelectedIndex < 0)
                {
                    throw new Exception("请选择正确的数据类型");
                }
                #endregion

                #region 字节偏移量
                if (!int.TryParse(this.txtOffsetByte.Text, out var offsetByte))
                {
                    throw new Exception(@"字节偏移量格式不正确,请重新输入");
                }

                if (offsetByte < 0)
                {
                    throw new Exception(@"字节偏移量必须大于等于零,请重新输入");
                }
                #endregion

                #region 位偏移量
                if (!int.TryParse(this.txtOffsetBit.Text, out var offsetBit))
                {
                    throw new Exception(@"位偏移量格式不正确,请重新输入");
                }

                if (offsetBit < 0 || offsetBit > 7)
                {
                    throw new Exception(@"位偏移量超出范围[0,7],请重新输入");
                }
                #endregion

                #region 字符串长度
                if (!int.TryParse(this.txtStringLength.Text, out var stringLength))
                {
                    throw new Exception(@"字符串长度格式不正确,请重新输入");
                }

                var selectedDataType = (DataType)Enum.Parse(typeof(DataType), this.cboxDataType.SelectedItem.ToString());
                if (selectedDataType == DataType.String)
                {
                    if (stringLength <= 0)
                    {
                        throw new Exception(@"字符串长度必须大于等,请重新输入");
                    }
                }
                else
                {
                    if (stringLength < 0)
                    {
                        throw new Exception(@"字符串长度必须大于等,请重新输入");
                    }
                }
                #endregion

                #region 字节溢出
                var name  = this.tabDisplay.SelectedTab.Name;
                var block = this.m_BlockDict[name];
                if (offsetByte + stringLength >= block.Length)
                {
                    throw new Exception(@"字节偏移量 + 字符串长度必须小于块大小,请重新输入");
                }
                #endregion

                //var selectedDataType = (DataType)Enum.Parse(typeof(DataType), this.cboxDataType.SelectedItem.ToString());
                switch (selectedDataType)
                {
                case DataType.Bit:
                    this.txtValue.Text = S7.GetBitAt(block, offsetByte, offsetBit).ToString();
                    break;

                case DataType.Byte:
                    this.txtValue.Text = S7.GetUSIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Ushort:
                    this.txtValue.Text = S7.GetUIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Uint:
                    this.txtValue.Text = S7.GetUDIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Ulong:
                    this.txtValue.Text = S7.GetULIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Sbyte:
                    this.txtValue.Text = S7.GetSIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Short:
                    this.txtValue.Text = S7.GetIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Int:
                    this.txtValue.Text = S7.GetDIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Long:
                    this.txtValue.Text = S7.GetLIntAt(block, offsetByte).ToString();
                    break;

                case DataType.Float:
                    this.txtValue.Text = S7.GetRealAt(block, offsetByte).ToString(CultureInfo.InvariantCulture);
                    break;

                case DataType.Double:
                    this.txtValue.Text = S7.GetLRealAt(block, offsetByte).ToString(CultureInfo.InvariantCulture);
                    break;

                case DataType.String:
                    var byteArr = new byte[stringLength];
                    Array.Copy(block, offsetByte, byteArr, 0, stringLength);
                    this.txtValue.Text = System.Text.Encoding.ASCII.GetString(byteArr);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #17
0
        private bool GetValue(int S7Type, int Pos, byte[] Buffer, ref string TxtValue)
        {
            /*
             * 0 Byte    8 Bit Word                     (All)
             * 1 Word   16 Bit Word                     (All)
             * 2 DWord  32 Bit Word                     (All)
             * 3 LWord  64 Bit Word                     (S71500)
             * 4 USint   8 Bit Unsigned Integer         (S71200/1500)
             * 5 UInt   16 Bit Unsigned Integer         (S71200/1500)
             * 6 UDInt  32 Bit Unsigned Integer         (S71200/1500)
             * 7 ULint  64 Bit Unsigned Integer         (S71500)
             * 8 Sint    8 Bit Signed Integer           (S71200/1500)
             * 9 Int    16 Bit Signed Integer           (All)
             * 10 DInt   32 Bit Signed Integer           (S71200/1500)
             * 11 LInt   64 Bit Signed Integer           (S71500)
             * 12 Real   32 Bit Floating point           (All)
             * 13 LReal  64 Bit Floating point           (S71200/1500)
             * 14 Time   32 Bit Time elapsed ms          (All)
             * 15 LTime  64 Bit Time Elapsed ns          (S71500)
             * 16 Date   16 Bit days from 1990/1/1       (All)
             * 17 TOD    32 Bit ms elapsed from midnight (All)
             * 18 DT      8 Byte Date and Time           (All)
             * 19 LTOD   64 Bit time of day (ns)         (S71500)
             * 20 DTL    12 Byte Date and Time Long      (S71200/1500)
             * 21 LDT    64 Bit ns elapsed from 1970/1/1 (S71500)
             * 22 Bit
             */


            //When WordLen = S7WLBit the Offset(Start) must be expressed in bits.Ex.The Start for DB4.DBX 10.3 is (10 * 8) + 3 = 83.

            switch (S7Type)
            {
            case 0:
            {
                TxtValue = System.Convert.ToString(Buffer[Pos], 10).ToUpper();
                break;
            }

            case 1:
            {
                UInt16 Word = S7.GetWordAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(Word, 10).ToUpper();
                break;
            }

            case 2:
            {
                UInt32 DWord = S7.GetDWordAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(DWord, 10).ToUpper();
                break;
            }

            case 3:
            {
                UInt64 LWord = S7.GetLWordAt(Buffer, Pos);
                TxtValue = System.Convert.ToString((Int64)LWord, 10).ToUpper();         // <-- Convert.ToString does not handle UInt64
                break;
            }

            case 4:
            {
                UInt16 USInt = S7.GetUSIntAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(USInt);
                break;
            }

            case 5:
            {
                UInt16 UInt = S7.GetUIntAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(UInt);
                break;
            }

            case 6:
            {
                UInt32 UDInt = S7.GetDWordAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(UDInt);
                break;
            }

            case 7:
            {
                UInt64 ULInt = S7.GetLWordAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(ULInt);
                break;
            }

            case 8:
            {
                int SInt = S7.GetSIntAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(SInt);
                break;
            }

            case 9:
            {
                int S7Int = S7.GetIntAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(S7Int);
                break;
            }

            case 10:
            {
                int DInt = S7.GetDIntAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(DInt);
                break;
            }

            case 11:
            {
                Int64 LInt = S7.GetLIntAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(LInt);
                break;
            }

            case 12:
            {
                Single S7Real = S7.GetRealAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(S7Real);
                break;
            }

            case 13:
            {
                Double S7LReal = S7.GetLRealAt(Buffer, Pos);
                TxtValue = System.Convert.ToString(S7LReal);
                break;
            }

            case 14:
            {
                Int32 TimeElapsed = S7.GetDIntAt(Buffer, Pos);
                // TIME type is a 32 signed number of ms elapsed
                // Can be added to a DateTime or used as Value.
                TxtValue = System.Convert.ToString(TimeElapsed) + "MS";
                break;
            }

            case 15:
            {
                Int64 TimeElapsed = S7.GetLIntAt(Buffer, Pos);
                // LTIME type is a 64 signed number of ns elapsed
                // Can be added (after a conversion) to a DateTime or used as Value.
                TxtValue = System.Convert.ToString(TimeElapsed) + "NS";
                break;
            }

            case 16:
            {
                DateTime DATE = S7.GetDateAt(Buffer, Pos);
                TxtValue = DATE.ToString("D#yyyy-MM-dd");
                break;
            }

            case 17:
            {
                DateTime TOD = S7.GetTODAt(Buffer, Pos);
                TxtValue = TOD.ToString("TOD#HH:mm:ss.fff");
                break;
            }

            case 18:
            {
                DateTime DT = S7.GetDateTimeAt(Buffer, Pos);
                TxtValue = DT.ToString("DT#yyyy-MM-dd-HH:mm:ss.fff");
                break;
            }

            case 19:
            {
                DateTime LTOD = S7.GetLTODAt(Buffer, Pos);
                TxtValue = LTOD.ToString("LTOD#HH:mm:ss.fffffff");
                break;
            }

            case 20:
            {
                DateTime DTL = S7.GetDTLAt(Buffer, Pos);
                TxtValue = DTL.ToString("DTL#yyyy-MM-dd-HH:mm:ss.fffffff");
                break;
            }

            case 21:
            {
                DateTime LDT = S7.GetLDTAt(Buffer, Pos);
                TxtValue = LDT.ToString("LDT#yyyy-MM-dd-HH:mm:ss.fffffff");
                break;
            }

            case 22:
            {
                bool bit = S7.GetBitAt(Buffer, Pos, 0);
                TxtValue = bit.ToString();
                break;
            }

            default:
                return(false);
            }

            return(true);
        }
        private void LetturaDatiEInvio()
        {
            try
            {
                resultdb1 = Client.DBRead(1, 0, db1Buffer.Length, db1Buffer);
                resultdb2 = Client.DBRead(2, 0, db2Buffer.Length, db2Buffer);

                if (resultdb1 == 0 && resultdb2 == 0)
                {
                    jh = new JsonHistory();
                    js = new JsonStatus();

                    //LEGGO I DATI DAL PLC
                    jh.quantita_prevista = S7.GetDIntAt(db1Buffer, 104);
                    jh.data_consegna     = S7.GetStringAt(db1Buffer, 218);
                    jh.data_esecuzione   = S7.GetStringAt(db1Buffer, 250);

                    //manipolazione date in anno-mese-giorno
                    DateTime tmpC = Convert.ToDateTime(jh.data_consegna);
                    jh.data_consegna = tmpC.ToString("yyyy-MM-dd HH:mm:ss");
                    DateTime tmpE = Convert.ToDateTime(jh.data_esecuzione);
                    jh.data_esecuzione = tmpE.ToString("yyyy-MM-dd HH:mm:ss");

                    jh.codice_commessa           = S7.GetStringAt(db2Buffer, 0);
                    jh.articolo                  = S7.GetStringAt(db2Buffer, 52);
                    jh.quantita_prodotta         = S7.GetDIntAt(db2Buffer, 104);
                    jh.quantita_scarto_pieno     = S7.GetDIntAt(db2Buffer, 108);
                    jh.quantita_scarto_difettoso = S7.GetDIntAt(db2Buffer, 112);

                    //Settaggio stato macchina e allarmi
                    int statusMacchina = S7.GetUSIntAt(db2Buffer, 116);
                    js.stato    = GetStatusMacchina(statusMacchina);
                    js.velocita = S7.GetDIntAt(db2Buffer, 118);
                    int codiceAllarme = S7.GetUSIntAt(db2Buffer, 232);
                    js.allarme = GetAllarmi(codiceAllarme);

                    //invio dati solo se è presente una commessa con codice non vuoto, oppure se è la prima con codice vuoto dopo almeno una normale
                    if ((jh.codice_commessa == "" && !invioCommessaVuota) || jh.codice_commessa != "")
                    {
                        //CONVERTO I DATI LETTI IN STRINGHE JSON
                        string jsonstato = JsonConvert.SerializeObject(js);

                        //INVIO I JSON ALLE API POST DEL MONGODB
                        SendHistoryJsonToAPI(jh);
                        SendStatusJsonToAPI(jsonstato);

                        EventLog appEventLog2 = new EventLog("Application");
                        appEventLog2.Source = "Timer Servizio Dati MongoDB";
                        appEventLog2.WriteEntry($"{jh.codice_commessa}", EventLogEntryType.Error);
                        //set della booleana per sapere se è già stata inviata una commessa vuota
                        if (jh.codice_commessa == "")
                        {
                            invioCommessaVuota = true;
                        }
                        else
                        {
                            invioCommessaVuota = false;
                        }
                    }
                }
                else
                {
                    EventLog appEventLog2 = new EventLog("Application");
                    appEventLog2.Source = "Timer Servizio Dati MongoDB";
                    appEventLog2.WriteEntry($"no connection", EventLogEntryType.Error);
                }
            }
            catch (Exception)
            {
                Client.Disconnect();
                connessione = false;
            }
        }
Пример #19
0
        static void ReadDB1005(S7Client client)
        {
            byte[] Buffer = new byte[65536];
            var    res    = client.DBRead(1005, 0, 1024, Buffer);

            if (res > 0)
            {
                Console.WriteLine(client.ErrorText(res));
            }
            var CXNCKD = S7.GetIntAt(Buffer, 42);

            Console.WriteLine(string.Format("一号线-车辆车厢内侧宽度:{0}", CXNCKD));

            var CXNCCD = S7.GetIntAt(Buffer, 40);

            Console.WriteLine(string.Format("一号线-车辆车厢内侧长度:{0}", CXNCCD));

            var CKGD = S7.GetIntAt(Buffer, 6);

            Console.WriteLine(string.Format("一号线-车框高度:{0}", CKGD));

            var SDZCBS = S7.GetIntAt(Buffer, 36);

            Console.WriteLine(string.Format("一号线-设定装车包数:{0}", SDZCBS));

            var JHZQCS = S7.GetIntAt(Buffer, 34);

            Console.WriteLine(string.Format("一号线-计划抓取次数:{0}", JHZQCS));

            var DQZCSKZL = S7.GetIntAt(Buffer, 176);

            Console.WriteLine(string.Format("一号线-当前装车刷卡重量:{0}", DQZCSKZL));

            var ZZCS = S7.GetDIntAt(Buffer, 138);

            Console.WriteLine(string.Format("一号线-总装车数:{0}", ZZCS));

            var DTZCS = S7.GetIntAt(Buffer, 142);

            Console.WriteLine(string.Format("一号线-当天装车数:{0}", DTZCS));

            var ZZCZL = S7.GetRealAt(Buffer, 158);

            Console.WriteLine(string.Format("一号线-总装车重量:{0}", ZZCZL));

            var DTZCZL = S7.GetRealAt(Buffer, 162);

            Console.WriteLine(string.Format("一号线-当天装车重量:{0}", DTZCZL));

            var JCSJHG = S7.GetBitAt(Buffer, 70, 2);

            Console.WriteLine(string.Format("一号线-检测数据合格:{0}", JCSJHG));

            var WMBXZHG = S7.GetBitAt(Buffer, 70, 3);

            Console.WriteLine(string.Format("一号线-尾门板X值合格:{0}", WMBXZHG));

            var DQZCZL = S7.GetDIntAt(Buffer, 0);

            Console.WriteLine(string.Format("一号线-当前装车重量:{0}", DQZCZL));

            var CPH = S7.GetStringAt(Buffer, 180, Encoding.GetEncoding("GB2312"));

            Console.WriteLine(string.Format("一号线-车牌号:{0}", CPH));
        }
Пример #20
0
 public void TestGetDIntAt(byte[] buffer, int pos, int expected)
 {
     S7.GetDIntAt(buffer, pos).ShouldBe(expected);
 }
Пример #21
0
    // Thread to Process PLC Read Queue
    static void ProcessPLC(S7PLC plc)
    {
        do
        {
            try
            {
                System.Threading.Thread.Sleep(5000);
                S7Client client = new S7Client();
                client.SetConnectionType(System.Convert.ToUInt16(plc.connection_type));
                client.SetConnectionParams(plc.ip, System.Convert.ToUInt16(plc.local_tsap), System.Convert.ToUInt16(plc.remote_tsap));
                Console.WriteLine("Try to connect " + plc.server_name);
                int res = client.Connect();
                if (res != 0 || client.Connected == false)
                {
                    continue;
                }

                Console.WriteLine("Connected " + plc.server_name + " IP:" + plc.ip);
                S7Client.S7CpuInfo Info = new S7Client.S7CpuInfo();
                res = client.GetCpuInfo(ref Info);
                if (res == 0)
                {
                    Console.WriteLine(plc.server_name + "  Module Type Name : " + Info.ModuleTypeName);
                    Console.WriteLine(plc.server_name + "  Serial Number    : " + Info.SerialNumber);
                    Console.WriteLine(plc.server_name + "  AS Name          : " + Info.ASName);
                    Console.WriteLine(plc.server_name + "  Module Name      : " + Info.ModuleName);
                }
                ;
                System.Threading.Thread.Sleep(1000);

                while (client.Connected)
                {
                    foreach (S7RW read in plc.reads)
                    {
                        CheckCommand(client, plc);
                        byte[] Buffer    = new byte[1024];
                        int    BytesRead = 0;
                        res = client.ReadArea(
                            System.Convert.ToInt32(read.data_area),
                            System.Convert.ToInt32(read.db),
                            System.Convert.ToInt32(read.offset),
                            System.Convert.ToInt32(read.amount),
                            System.Convert.ToInt32(StringToWordLengthCode(read.data_type)),
                            Buffer,
                            ref BytesRead);
                        if (res == 0)
                        {
                            // HexDump(Buffer, BytesRead);
                            for (int i = 0; i < read.amount; i++)
                            {
                                int    bytecnt;
                                double value = 0;
                                switch (read.data_type)
                                {
                                case "BIT":
                                    bytecnt = i / 8;
                                    value   = System.Convert.ToDouble(S7.GetBitAt(Buffer, bytecnt, i % 8));
                                    break;

                                case "BYTE":
                                    bytecnt = i;
                                    value   = S7.GetByteAt(Buffer, bytecnt);
                                    break;

                                case "CHAR":
                                    bytecnt = i;
                                    value   = S7.GetByteAt(Buffer, bytecnt);
                                    break;

                                case "WORD":
                                    bytecnt = i * 2;
                                    value   = S7.GetWordAt(Buffer, bytecnt);
                                    break;

                                case "DWORD":
                                    bytecnt = i * 4;
                                    value   = S7.GetDWordAt(Buffer, bytecnt);
                                    break;

                                case "INT":
                                    bytecnt = i * 2;
                                    value   = S7.GetIntAt(Buffer, bytecnt);
                                    break;

                                case "DINT":
                                    bytecnt = i * 4;
                                    value   = S7.GetDIntAt(Buffer, bytecnt);
                                    break;

                                case "REAL":
                                    bytecnt = i * 4;
                                    value   = S7.GetRealAt(Buffer, bytecnt);
                                    break;

                                case "COUNTER":
                                    bytecnt = i * 2;
                                    value   = S7.GetCounter((ushort)((Buffer[bytecnt + 1] << 8) + (Buffer[bytecnt])));
                                    break;

                                case "TIMER":
                                    bytecnt = i * 2;
                                    value   = (ushort)((Buffer[bytecnt + 1] << 8) + (Buffer[bytecnt]));
                                    break;

                                default:
                                    Console.WriteLine("Unsupported data type: " + read.data_type);
                                    break;
                                }
                                SendUdp(Encoding.ASCII.GetBytes(
                                            "[{\"point_key\":" + (read.point_number + i) +
                                            ",\"value\":" + value +
                                            ",\"failed\":false" +
                                            "}]"));
                                if (logread)
                                {
                                    Console.WriteLine(plc.server_name + " " + read.name + " OSHMI_POINT_NUMBER=" + (read.point_number + i) + " VALUE=" + value + " " + read.data_type);
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine(plc.server_name + " Error " + read.name);
                        }
                        System.Threading.Thread.Sleep(System.Convert.ToInt32(read.delay_ms));
                    }
                }

                // client.Disconnect();
                Console.WriteLine("Disconnected " + plc.server_name);
            }
            catch (Exception e)
            {
                // EXCEPTION HANDLER
                Console.WriteLine("Exception " + plc.server_name);
                Console.WriteLine(e);
            }
            System.Threading.Thread.Sleep(10000);
        } while (true);
    }
Пример #22
0
        /// <summary>
        /// ???
        /// </summary>
        public static List <string> ReplaceCharByValues(byte[] buf, List <string> tab)
        {
            // ??
            int           offset   = 0;
            int           cntBool  = 0;
            List <string> listTemp = new List <string>();

            for (int i = 0; i < tab.Count; i++)
            {
                // For Bool
                if (tab[i] == "BOOL")
                {
                    bool tempB;
                    //int offsetB = 5;
                    tempB = S7.GetBitAt(buf, offset, cntBool);
                    listTemp.Add(tempB.ToString());

                    cntBool++; // Incrément compteur booléen
                    if (cntBool == 8)
                    {
                        offset++;
                        cntBool = 0;
                    }
                }
                // For Byte
                if (tab[i] == "BYTE")
                {
                    int tempB;
                    tempB = S7.GetByteAt(buf, offset);
                    listTemp.Add("B#16#" + "0");
                    cntBool = 0;

                    offset = offset + 2;
                }
                // For Word
                if (tab[i] == "WORD")
                {
                    int tempW;
                    tempW = S7.GetWordAt(buf, offset);
                    listTemp.Add("W#16#" + "0");
                    cntBool = 0;

                    offset = offset + 2;
                }
                // For Int
                if (tab[i] == "INT")
                {
                    int tempI;
                    tempI = S7.GetIntAt(buf, offset);
                    listTemp.Add(tempI.ToString());
                    cntBool = 0;

                    offset = offset + 2;
                }
                // For DInt
                if (tab[i] == "DINT")
                {
                    double tempDI;
                    tempDI = S7.GetDIntAt(buf, offset);
                    listTemp.Add(tempDI.ToString());
                    cntBool = 0;

                    offset = offset + 4;
                }
                // For Real
                if (tab[i] == "REAL")
                {
                    double tempR;
                    float  tempFR, test;
                    tempR  = S7.GetRealAt(buf, offset);
                    tempFR = Convert.ToSingle(tempR);
                    test   = (float)(Math.Truncate((double)tempFR * 100.0) / 100.0);
                    listTemp.Add(tempR.ToString("0.00"));
                    cntBool = 0;

                    offset = offset + 4;
                }
            }

            return(listTemp);
        }
Пример #23
0
        private void ReadPLC()
        {
            // Connect if disconnected
            if (!client.Connected)
            {
                client.Connect();
            }

            //Do this for each DB in the configuration
            foreach (var db in configService.ActiveConfig.DBReads)
            {
                Byte[] buffer    = new byte[db.DBLengthByte];
                var    ret       = client.DBRead(db.DBNumber, db.DBOffsetByte, db.DBLengthByte, buffer);
                var    errorText = client.ErrorText(ret);
                if (ret == 0)
                {
                    Console.WriteLine($"Reading DB{db.DBNumber} success.");
                }
                else
                {
                    Console.WriteLine($"Reading DB{db.DBNumber} failed, error {ret}:, {errorText}");
                }

                //Parse the db into parts
                foreach (var tag in db.Tags)
                {
                    switch (tag.Type)
                    {
                    case "Bool":
                        tag.Data = S7.GetBitAt(buffer, tag.OffsetByte, tag.OffsetBit);
                        break;

                    case "Int8":
                        tag.Data = S7.GetByteAt(buffer, tag.OffsetByte);
                        break;

                    case "Int16":
                        tag.Data = S7.GetIntAt(buffer, tag.OffsetByte);
                        break;

                    case "Int32":
                        tag.Data = S7.GetDIntAt(buffer, tag.OffsetByte);
                        break;

                    case "Int64":
                        tag.Data = S7.GetLIntAt(buffer, tag.OffsetByte);
                        break;

                    case "Float":
                        tag.Data = S7.GetRealAt(buffer, tag.OffsetByte);
                        break;

                    case "Double":
                        tag.Data = S7.GetLRealAt(buffer, tag.OffsetByte);
                        break;

                    case "String":
                        tag.Data = S7.GetCharsAt(buffer, tag.OffsetByte, tag.StringLength);
                        break;

                    default:
                        Console.WriteLine($"Unknown type for tag {tag.Name}");
                        break;
                    }
                }
            }
        }
Пример #24
0
        public void ReadFromByteArray(byte[] data)
        {
            var walker = new JPLC_BASEWalker(this, OrderedProperties);

            //===================================================================
            // BOOL
            //===================================================================
            walker.BooleanFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <bool> JPLCProperty = propertyWrapper.Property as JPLCProperty <bool>;
                // int bitNumber = (int)((offsetFromStartOfWalk - (int)offsetFromStartOfWalk)*10); // (2.3 -2)*10 = 3
                // int bitNumber = (int)((offsetFromStartOfWalk * 1.0 - ((int)offsetFromStartOfWalk * 1.0)) * 10.0); // (2.3 -2)*10 = 3
                double truncatedOffset = Math.Truncate(offsetFromStartOfWalk);
                double difference      = Math.Round((offsetFromStartOfWalk - truncatedOffset) * 10);
                int    bitNumber       = (int)(difference); // (2.3 -2)*10 = 3
                JPLCProperty.Value = S7.GetBitAt(data, (int)offsetFromStartOfWalk, bitNumber);
            };

            //===================================================================
            // BYTE
            //===================================================================
            walker.ByteFound += (propertyWrapper, offsetFromStartOfWalk) =>
            {
                JPLCProperty <byte> JPLCProperty = propertyWrapper.Property as JPLCProperty <byte>;
                JPLCProperty.Value = S7.GetByteAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // INT
            //===================================================================
            walker.IntegerFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <int> JPLCProperty = propertyWrapper.Property as JPLCProperty <int>;
                JPLCProperty.Value = S7.GetDIntAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // REAL
            //===================================================================
            walker.RealFound += (propertyWrapper, offsetFromStartOfWalk) =>
            {
                JPLCProperty <float> JPLCProperty = propertyWrapper.Property as JPLCProperty <float>;
                JPLCProperty.Value = S7.GetRealAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // SHORT
            //===================================================================
            walker.ShortFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <short> JPLCProperty = propertyWrapper.Property as JPLCProperty <short>;
                JPLCProperty.Value = (short)S7.GetIntAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // DATETIME
            //===================================================================
            walker.DateTimeFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <DateTime> JPLCProperty = propertyWrapper.Property as JPLCProperty <DateTime>;
                JPLCProperty.Value = S7.GetDateTimeAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // DATE
            //===================================================================
            walker.DateFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <S7Date> JPLCProperty = propertyWrapper.Property as JPLCProperty <S7Date>;
                JPLCProperty.Value      = new S7Date();
                JPLCProperty.Value.Date = S7.GetDateAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // TIME
            //===================================================================
            walker.TimeFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <S7Time> JPLCProperty = propertyWrapper.Property as JPLCProperty <S7Time>;
                JPLCProperty.Value      = new S7Time();
                JPLCProperty.Value.Time = S7.GetTODAt(data, (int)offsetFromStartOfWalk);
            };

            //===================================================================
            // UDT
            //===================================================================
            walker.UDTFound += (propertyWrapper, offsetFromStartOfWalk) =>
            {
                //  Console.WriteLine(propertyWrapper.Property);
                var    udt = (propertyWrapper.PropertyType.GetProperty("Value").GetValue(propertyWrapper.Property, null)) as JPLC_BASE;
                byte[] extractedByteArray = data.Skip((int)offsetFromStartOfWalk).Take(udt.SizeInBytes).ToArray();
                udt.ReadFromByteArray(extractedByteArray);
            };

            //===================================================================
            // STRING
            //===================================================================
            walker.StringFound += (propertyWrapper, offsetFromStartOfWalk) => {
                JPLCProperty <string> JPLCProperty = propertyWrapper.Property as JPLCProperty <string>;
                JPLCProperty.Value = S7.GetStringAt(data, (int)offsetFromStartOfWalk);
            };

            walker.Walk();
        }