示例#1
0
        public void SendCommand(byte[] tosend)
        {
            List <byte> TmpBuf = new List <byte>();

            byte[] crc = Crc16.ComputeChecksumBytes(tosend);
            for (int i = 0; i < tosend.Length; i++)
            {
                if (tosend[i] == 0x7e || tosend[i] == 0x7d)
                {
                    TmpBuf.Add(0x7d);
                    TmpBuf.Add((byte)(tosend[i] ^ 0x20));
                }
                else
                {
                    TmpBuf.Add(tosend[i]);
                }
            }
            for (int i = 0; i < 2; i++)
            {
                if (crc[i] == 0x7e || crc[i] == 0x7d)
                {
                    TmpBuf.Add(0x7d);
                    TmpBuf.Add((byte)(crc[i] ^ 0x20));
                }
                else
                {
                    TmpBuf.Add(crc[i]);
                }
            }
            TmpBuf.Add(0x7e);
            RxClear();
            SendBytes(TmpBuf.ToArray());
        }
        /// <summary>
        /// Серелизация класса
        /// </summary>
        private void Сlass_Deserialization(byte[] date)
        {
            try
            {
                logger.Info("Формирование класса:");

                Stream          stream    = new MemoryStream(date);
                BinaryFormatter formatter = new BinaryFormatter();

                metaClass = (MetaClassForStructandtherdata)formatter.Deserialize(stream);

                logger.Info("Сформирован мета-класс");
                //После обработки статус меняется на свободный
                SignalFormedMetaClass?.Invoke(metaClass.struct_which_need_transfer);   // 2.Вызов события
                logger.Info("Вызвано события на изменения");

                //Контрольная сумма
                Crc16  crc16      = new Crc16();
                byte[] crc16bytes = crc16.ComputeChecksumBytes(date);

                cr16 = crc16.convertoshort(crc16bytes);
                logger.Info("Сформирована контрольная сумма");

                slave.DataStore.HoldingRegisters[1] = SlaveState.havechecktotime;
                logger.Info("В регистр состояние готов принимать пакеты" + slave.DataStore.HoldingRegisters[1]);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.WriteLine(ex);
            }
        }
        public static string ToCrc16(this string s)
        {
            if (s.IsNullOrEmpty())
            {
                return("");
            }

            byte[] crc = _crc16.ComputeChecksumBytes(Encoding.UTF8.GetBytes(s));
            return(crc[0].ToString("x2") + crc[1].ToString("x2"));
        }
示例#4
0
        public void Init()
        {
            byte head  = (byte)(_updateSSO ? 1 : 0);
            var  track = _w.Track;

            _w.HeadLoad       = true;
            _w.RecordNotFound = false;
            _steps[0]         = track;
            _steps[1]         = head;
            _steps[2]         = _w.Sector;
            _steps[3]         = (byte)_w.Disk.GetSectorSize(head, track).AltSizeField;

            var crc16 = new Crc16(InitialCrcValue.NonZero1);
            var crc   = crc16.ComputeChecksumBytes(_steps, 4);

            _steps[4] = crc[0];
            _steps[5] = crc[1];
        }
示例#5
0
        public byte[] EncryptMessage(byte[] data)
        {
            var temp = data.ToList();
            var rest = data.Length % 8;

            for (int i = 0; i < 8 - rest; i++)
            {
                temp.Add(0);
            }
            var encrypt = _xtea.Encrypt(temp.ToArray());
            var hex     = BytesToHexString(encrypt);
            var crc     = Crc16.ComputeChecksumBytes(hex);
            var all     = new List <byte>();

            all.AddRange(hex);
            all.AddRange(BytesToHexString(crc));
            all.Add(Protocol.END);
            return(all.ToArray());
        }
示例#6
0
 public static byte[] ComputeCrc16ChecksumBytes(byte[] bytes)
 {
     return
         (_crc16.ComputeChecksumBytes(bytes));
 }
示例#7
0
        private void Checksum()
        {
            try
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    sim.length   = new System.IO.FileInfo(this.ofd.FileName).Length; // calculate file lenght
                    sim.buffFull = File.ReadAllBytes(ofd.FileName);                  // read full file
                    if (sim.length != 262144 && sim.length != 24576)                 // test if file has correct size
                    {
                        label1.Text = "Wrong filesize: " + sim.length;
                        return;
                    }
                    // make sure this is false in case user opens more than one files
                    richTextBox1.Text = "";
                    label1.Text       = ofd.SafeFileName;
                    sim.chksumcorr    = false;
                    sim.NumberOfChecksumsCorrected = 0;

                    if (sim.length == 262144)
                    {
                        if (ChecksumBootSector())
                        {
                            sim.NumberOfChecksumsCorrected++;
                        }
                        if (ChecksumProgram())
                        {
                            sim.NumberOfChecksumsCorrected++;
                        }
                    }

                    // Find MS41 Checksum
                    byte[] ToFind = new byte[] { 0x4E, 0x00, 0xFF, 0xFF };
                    int    Start  = IndexOfBytes(sim.buffFull, ToFind, -0x1, (int)sim.length - 1);
                    if (Start == -1)
                    {
                        richTextBox1.Text += "No MS41 checksum in this file\r\n";
                        return;
                    }
                    //richTextBox1.Text += "Found MS41 checksum at: 0x" + Start.ToString("X5") + "\r\n";

                    // Find initial Value
                    byte[] Initial_Value = new byte[0x2];
                    Buffer.BlockCopy(sim.buffFull, Start + 0x0E, Initial_Value, 0x0, 0x2);
                    Array.Reverse(Initial_Value);
                    sim.initial = BitConverter.ToUInt16(Initial_Value, 0);
                    ushort num = BitConverter.ToUInt16(Initial_Value, 0);
                    //richTextBox1.Text += "Found initial Value: 0x" + sim.initial.ToString("X2") + "\r\n\r\n";


                    int[,] Checksums;
                    Checksums = new int[20, 5]; // declare array of 20 rows and 3 colums
                    // checksum number /checksum addr / checksum file /checksum calculated /checksum bytes
                    int  StartZ   = Start;
                    bool Evaluate = false;

                    for (int i = 1; i != 20; i++)
                    {
                        // Checksum Start
                        ushort SS = BitConverter.ToUInt16(sim.buffFull, StartZ);
                        if (SS == 0xFFFF)
                        {
                            break;                      // break if end of checksum
                        }
                        Checksums[i, 1] = (Start + SS); // put checksum start adress into array

                        // Calculate checksums + store in array Checksums at colum 3
                        int    ChkSumSize  = ((Start + SS) - StartZ); // calculate how many checksum bytes
                        Crc16  crc         = new Crc16();
                        byte[] chksumblock = new byte[ChkSumSize];
                        Buffer.BlockCopy(sim.buffFull, StartZ, chksumblock, 0x0, ChkSumSize);
                        Checksums[i, 3] = BitConverter.ToUInt16(crc.ComputeChecksumBytes(chksumblock, num), 0);


                        // Read checksum
                        //ushort RS = BitConverter.ToUInt16(sim.buffFull, Start + SS);
                        int RS = ReverseBytes(BitConverter.ToUInt16(sim.buffFull, Start + SS));
                        Checksums[i, 2] = RS;      // put it into array

                        StartZ = (Start + SS + 2); // calculate adress for reading next start value

                        // Check if checksums are correct or not and update them in sim.buffull if wrong
                        if (Checksums[i, 2] == Checksums[i, 3])
                        {
                            Evaluate = true;
                        }
                        else
                        {
                            Evaluate = false;
                            byte[] update = new byte[2];
                            update = BitConverter.GetBytes(ReverseBytes((ushort)Checksums[i, 3]));
                            // copy back to array
                            //Array.Reverse(update);
                            Buffer.BlockCopy(update, 0, sim.buffFull, Checksums[i, 1], 2);

                            // make sure checksums gets corrected
                            sim.chksumcorr = true;
                            // update number of wrong checksums detected
                            sim.NumberOfChecksumsCorrected++;

                            // debug

                            /*
                             * ushort tempor = BitConverter.ToUInt16(update, 0);
                             * MessageBox.Show(tempor.ToString("X2"),
                             * "Important Message");
                             */
                        }

                        //  Update Richtextbox
                        richTextBox1.Text += "Checksum " + i.ToString("D2") + " at 0x" + Checksums[i, 1].ToString("X5") +
                                             " Value: " + RS.ToString("X4") + " Comp: " + Checksums[i, 3].ToString("X4") +
                                             " BlockSize: " + ChkSumSize.ToString("X3");

                        if (Evaluate)
                        {
                            richTextBox1.AppendText("\t(Checksum OK)\r\n");
                        }
                        else
                        {
                            richTextBox1.AppendText("\t(Checksum ERROR)\r\n");
                        }
                    }

                    // save file if checksums are updated
                    if (sim.chksumcorr)
                    {
                        // debug File.WriteAllBytes(Path.ChangeExtension(ofd.FileName, ".ChksumCorrected"), sim.buffFull);
                        richTextBox1.Text         += "\r\n" + sim.NumberOfChecksumsCorrected.ToString() + " Checksum(s) Corrected!";
                        toolStripMenuItem3.Enabled = true;
                        toolStripMenuItem2.Enabled = true;
                    }
                    else
                    {
                        richTextBox1.Text += "\r\n" + sim.NumberOfChecksumsCorrected.ToString() + " Checksum(s) Corrected!";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#8
0
        public byte[] returnArrayBytesWithCRC16(byte[] inBytes)
        {
            Crc16 crc = new Crc16(Crc16Mode.CcittKermit);
            byte[] bytebegin = { DLE, STX };
            byte[] byteend = { DLE, ETX };

            byte[] tempb = returnWithOutDublicateETX(inBytes);
            var searchBegin = PatternAt(tempb, bytebegin);
            if (searchBegin == null)
                return null;

            var searchEnd = PatternAt(tempb, byteend);
            if (searchEnd == null)
                return null;

            var newArr = tempb.Skip((int)searchBegin + 2).Take((int)searchEnd - 2).ToArray();

            byte[] a = new byte[newArr.Length + 1];
            newArr.CopyTo(a, 0);
            a[newArr.Length] = ETX;

            //var control = tempb.Skip((int)searchEnd + 2).Take(2).ToArray();

            byte[] crcBytes = crc.ComputeChecksumBytes(a);
            byte[] retBytes = new byte[inBytes.Length + 2];
            inBytes.CopyTo(retBytes, 0);
            retBytes[retBytes.Length - 2] = crcBytes[0];
            retBytes[retBytes.Length - 1] = crcBytes[1];
            return retBytes;
        }
        /// <summary>
        /// отправка инфоданных
        /// </summary>

        public void send_multi_message(MemoryStream stream)
        {
            ushort coilAddress = 10;

            byte[] date  = stream.ToArray();
            int    count = 50;

            count = (date.Length / 2) + 1;
            ushort[] date_modbus = new ushort[date.Length / 2 + 1];

            int needtopacketsend;

            //Кол-во переднных какналов за 1 запрос
            int count_send_packet = 70;

            ushort[] sentpacket = new ushort[count_send_packet];

            write_console(date);
            Console.WriteLine("");
            //конвертирует в ushort

            logger.Info("Преобразование в ushort:Начато");
            Buffer.BlockCopy(date, 0, date_modbus, 0, date.Length);
            logger.Info("Преобразование в ushort:закончено");


            write_console(date_modbus);

            byte[] date_unpack = new byte[date.Length];

            /*
             * Buffer.BlockCopy(date_modbus, 0, date_unpack, 0, date.Length);
             * Console.WriteLine("");
             * write_console(date_unpack);
             * Console.WriteLine("");
             */

            try
            {
                logger.Info("Запрос о получении статуса");
                status_slave = SendRequestforStatusSlave();
                logger.Info("Cтатус Slave " + status_slave);

                //есть свободное время у slave для отправки
                if (status_slave == SlaveState.have_free_time)
                {
                    logger.Info("Статус свободен:");

                    //SendStatusforSlave(SlaveState.havetimetransfer);

                    //Отправка кол-во байт
                    Sendpaketwithcountbytes(date.Length);

                    logger.Info("Статус свободен:");
                    logger.Info("Отправляем метапкет с кол-вом данных байт" + date.Length);
                    logger.Info("Отправляем метапкет с кол - вом данных ushort" + date_modbus.Length);

                    //Console.WriteLine("Отправляем метапкет с кол-вом данных байт"+ date.Length);
                    //Console.WriteLine("Отправляем метапкет с кол-вом данных ushort" + date_modbus.Length);

                    if (date_modbus.Length > count_send_packet)
                    {
                        //Console.WriteLine("Объем данных больше чем в пакете");
                        logger.Info("Объем данных больше чем в пакете");

                        int countneedsend = (date_modbus.Length / count_send_packet) + 1;
                        int k             = 0;
                        //Console.WriteLine("Будет отправлено " + countneedsend + " пакетов");
                        logger.Info("Будет отправлено " + countneedsend + " пакетов");

                        //кол-во отправок
                        for (int i = 0; i < countneedsend; i++)
                        {
                            int counter_reguest_status = 0;

                            //lonsole.WriteLine("Отправляем запрос о статусе");
                            logger.Info("Отправляем запрос о статусе");

                            status_slave = SendRequestforStatusSlave();

                            if (status_slave == SlaveState.havenot_time)
                            {
                                while (counter_reguest_status != 3)
                                {
                                    //Console.WriteLine("Отправляем запрос о статусе, так как был занят на "+i+" попытке");

                                    logger.Info("Отправляем запрос о статусе, так как был занят на " + i + " попытке");

                                    Thread.Sleep(1000);
                                    status_slave = SendRequestforStatusSlave();
                                    if (status_slave == SlaveState.have_free_time || status_slave == SlaveState.havetimetransfer)
                                    {
                                        counter_reguest_status = 3;
                                    }
                                    else
                                    {
                                        counter_reguest_status++;
                                    }
                                }
                                //если нет свободного статуса в течение 3 попыток идет прекращение передачи
                                if (status_slave == SlaveState.havenot_time)
                                {
                                    //Console.WriteLine("Попытка передачи не удалось на "+i+"передаче");
                                    logger.Warn("Отправляем запрос о статусе, так как был занят на " + i + " попытке");
                                }
                            }

                            if (status_slave == SlaveState.have_free_time || status_slave == SlaveState.havetimetransfer)
                            {
                                //окончание передачи
                                if (countneedsend - 1 == i)
                                {
                                    //Console.WriteLine("Отправка " + i + " пакета");
                                    logger.Trace("Отправка " + i + " пакета");
                                    for (int j = i * count_send_packet; j < date_modbus.Length; j++)
                                    {
                                        sentpacket[k] = date_modbus[j];
                                        k++;
                                    }
                                    //Console.WriteLine("Отправка данных");
                                    logger.Trace("Отправка данных");
                                    write_console(sentpacket);
                                    k = 0;
                                    //Console.WriteLine("Отправка данных");
                                    logger.Trace("Отправка данных");

                                    Console.WriteLine("Контрольная сумма");

                                    //если slave свободен то отправляем
                                    master.WriteMultipleRegisters(slaveID, coilAddress, sentpacket);
                                    //Console.WriteLine("Отправлено");

                                    logger.Trace("Отправлено");
                                    Thread.Sleep(500);

                                    //Контрольная сумма
                                    crc16 = new Crc16();
                                    byte[] controlsum16 = crc16.ComputeChecksumBytes(date);

                                    for (int cr1 = 0; cr1 < controlsum16.Length; cr1++)
                                    {
                                        Console.WriteLine(controlsum16[cr1]);
                                    }

                                    //Отправка контрольной суммы
                                    send_cr16_message(controlsum16);

                                    Console.WriteLine("Cформирован");
                                }
                                else
                                {
                                    //Console.WriteLine("Отправка " + i + " пакета");
                                    logger.Trace("Отправка " + i + " пакета");
                                    for (int j = i * count_send_packet; j < (i + 1) * count_send_packet; j++)
                                    {
                                        sentpacket[k] = date_modbus[j];
                                        k++;
                                    }
                                    //Console.WriteLine("Отправка данных");
                                    logger.Trace("Отправка данных");
                                    write_console(sentpacket);
                                    k = 0;
                                    //Console.WriteLine("Отправка данных");
                                    logger.Trace("Отправка данных");

                                    //если slave свободен то отправляем
                                    master.WriteMultipleRegisters(slaveID, coilAddress, sentpacket);
                                    //Console.WriteLine("Отправлено");

                                    logger.Trace("Отправлено");
                                    Thread.Sleep(500);
                                }

                                //status_slave = SendRequestforStatusSlave();
                            }
                            else
                            {
                                //Console.WriteLine("Slave занят: Передача отменена");
                                logger.Trace("Slave занят: Передача отменена");
                                counter_reguest_status = 0;
                            }
                        }
                        //после завершение отправки отправить запрос на проверку
                        //SendStatusforSlave(SlaveState.have_free_time);
                    }
                    else    //в случае если пакет меньше чем ограничения
                    {
                        logger.Trace("Передача меньше чем, пакет");
                        master.WriteMultipleRegisters(slaveID, coilAddress, date_modbus);
                    }
                }
                else  //В случае если не получено данные
                {
                    //Console.WriteLine("Пакет не может передаться, связи с тем, что Slave занят");
                    logger.Warn("Пакет не может передаться, связи с тем, что Slave занят");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                logger.Error(ex);
            }


            /*  обратная передача
             * Buffer.BlockCopy(date_modbus, 0, date_unpack, 0, date.Length);
             * byte[] date_unpack = new byte[date.Length];
             * Console.WriteLine("yes");
             */
        }