Click here to Skip to main content
15,888,579 members
Home / Discussions / C#
   

C#

 
AnswerRe: Suggestion to do a multilanguage project Pin
Bernhard Hiller15-Jan-12 21:31
Bernhard Hiller15-Jan-12 21:31 
GeneralRe: Suggestion to do a multilanguage project Pin
joost.versteegen16-Jan-12 4:26
joost.versteegen16-Jan-12 4:26 
AnswerRe: Suggestion to do a multilanguage project Pin
jschell16-Jan-12 8:52
jschell16-Jan-12 8:52 
QuestionProblem with Ninject Pin
venomation15-Jan-12 0:28
venomation15-Jan-12 0:28 
AnswerRe: Problem with Ninject Pin
Dave Kreskowiak15-Jan-12 3:23
mveDave Kreskowiak15-Jan-12 3:23 
QuestionRemote PC diagnostics Code Pin
Mohammed NAeem14-Jan-12 21:49
Mohammed NAeem14-Jan-12 21:49 
AnswerRe: Remote PC diagnostics Code Pin
Eddy Vluggen15-Jan-12 6:02
professionalEddy Vluggen15-Jan-12 6:02 
QuestionLooking for help deciphering this code class Pin
turbosupramk313-Jan-12 19:09
turbosupramk313-Jan-12 19:09 
Hi,

I know this may be asking a lot, I found this code class and it makes little sense to me in some places, so I was looking for some help deciphering it. It is designed to query a serial port and communicate with a microchip.


Some of the confusing parts Smile | :)

C#
private const uint COMMAND_LOAD_RAM_AND_RUN = 1;
        private const uint COMMAND_LOAD_EEPROM_AND_RUN = 3;


C#
lfsrData[0] = 0xF9;  // 0xF9 is 249 in hex
            for (int i = 1; i < 251; ++i)
                lfsrData[i] = (byte)(0xFE | (IterateLFSR() ? 1 : 0));   // 0xFE is 254 in hex


C#
byte[] buffer = new byte[258];
            for (int i = 0; i < 258; ++i)
                buffer[i] = 0xF9;   // 0xF9 is 249 in hex



This part really throws me ...

C#
for (int i = 0; i < 250; ++i)
           {
               if (ReceiveBit(false, 100) != IterateLFSR())
                   throw new ApplicationException("Receiving LFSR data failed!");
           }

           //Receive pr version
           byte version = 0;
           for (int i = 0; i < 8; ++i)
           {
               version >>= 1;
               version += (byte)(ReceiveBit(false, 100) ? 128 : 0);
           }




And here is the whole class itself, thank you for reading.

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Threading;

namespace PrBooter
{
    public class Booter
    {

        /// <summary>
        /// Creates the booter, but doesn't open serial port and won't do anything.
        /// </summary>
        /// <param name="portName">Eg. "COM1"</param>
        public Booter(string portName)
        {
            m_SerialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);
            m_SerialPort.ReadTimeout = 3000;
        }

        #region Constants
        private const uint COMMAND_LOAD_RAM_AND_RUN = 1;
        private const uint COMMAND_LOAD_EEPROM_AND_RUN = 3;
        #endregion

        private SerialPort m_SerialPort = null;

        #region Public stuff
        /// <summary>
        /// Just redirects to SerialPort.GetPortNames()
        /// </summary>
        /// <returns></returns>
        public static string[] GetPortNames()
        {
            return SerialPort.GetPortNames();
        }


        /// <summary>
        /// Gets or sets the portname (eg. "COM1")
        /// </summary>
        public string PortName
        {
            get { return m_SerialPort.PortName; }
            set
            {
                if (m_SerialPort.IsOpen)
                    throw new InvalidOperationException("Cannot set PortName while Serial is open!");
                m_SerialPort.PortName = value;
            }
        }


        public void ResetPr()
        {
            m_SerialPort.DtrEnable = true;
            Thread.Sleep(10); //Wait 10 msec
            m_SerialPort.DtrEnable = false;
        }

        /// <summary>
        /// Programs EEPROM and runs. 
        /// </summary>
        public void Reprogram(string filename)
        {
            Stream s = File.OpenRead(filename);
            try
            {
                Reprogram(s);
            }
            finally
            {
                s.Close();
            }
        }
        /// <summary>
        /// Programs EEPROM and runs. Doesn't close the stream!!
        /// </summary>
        /// <param name="stream"></param>
        public void Reprogram(Stream stream)
        {
            try
            {
                m_SerialPort.Open();
                byte[] programData = new byte[(int)stream.Length];
                stream.Read(programData, 0, (int)programData.Length);

                StartComm(COMMAND_LOAD_EEPROM_AND_RUN);
                SendProgram(programData);

                //Check EEPROM Checksums
                if (ReceiveBit(true, 5000))
                    throw new ApplicationException("EEPROM Programming Failed!");
                if (ReceiveBit(true, 2500))
                    throw new ApplicationException("EEPROM Verification Failed!");
            }
            finally
            {
                m_SerialPort.Close();
            }
        }

        /// <summary>
        /// Loads ram and runs
        /// </summary>
        /// <param name="filename"></param>
        public void Boot(string filename)
        {
            Stream s = File.OpenRead(filename);
            try
            {
                Boot(s);
            }
            finally
            {
                s.Close();
            }
        }

        /// <summary>
        /// Loads RAM and runs. Doesn't close the stream!
        /// </summary>
        /// <param name="stream"></param>
        public void Boot(Stream stream)
        {
            try
            {
                m_SerialPort.Open();
                byte[] programData = new byte[(int)stream.Length];
                stream.Read(programData, 0, (int)programData.Length);

                StartComm(COMMAND_LOAD_RAM_AND_RUN);
                SendProgram(programData);
            }
            finally
            {
                m_SerialPort.Close();
            }

        }

        #endregion

        #region High level protocol
        private void SendProgram(byte[] programData)
        {
            //Transmit number of LONGS in the image
            int longCount = (programData.Length + 3) >> 2;
            TransmitEncodedLong((uint)longCount);

            //Transmit the program image as encoded LONGs
            for (int i = 0; i < longCount; ++i)
            {
                int byteIdx = (i << 2);
                uint x = (uint)(
                    (programData[byteIdx + 3] << 24) |
                    (programData[byteIdx + 2] << 16) |
                    (programData[byteIdx + 1] << 8) |
                    (programData[byteIdx]));

                TransmitEncodedLong(x);
            }

            m_SerialPort.BaseStream.Flush();
            //Read a bit indicating whether checksum failed
            if (ReceiveBit(true, 2500))
            { //FAILED: 
                throw new ApplicationException("RAM Checksum failed!");
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        private int StartComm(uint command)
        {
            ResetPr(); // Sends a DTR enable/disable command
            Thread.Sleep(90); //Wait 100 msec. 
            ResetLFSR(); // Sets a byte to the ascii character value for the capital letter "P"
            //TX 1 Timing calibration (F9) and 250 bytes of LFSR data
            byte[] lfsrData = new byte[251]; // Sets this byte array to 251 bytes
            lfsrData[0] = 0xF9;  // 0xF9 is 249 in hex
            for (int i = 1; i < 251; ++i)
                lfsrData[i] = (byte)(0xFE | (IterateLFSR() ? 1 : 0));   // 0xFE is 254 in hex
            m_SerialPort.Write(lfsrData, 0, 251);

            //TX 258 timing calibrations
            byte[] buffer = new byte[258];
            for (int i = 0; i < 258; ++i)
                buffer[i] = 0xF9;   // 0xF9 is 249 in hex
            m_SerialPort.Write(buffer, 0, 258);

            m_SerialPort.BaseStream.Flush();

            //RX 250 bytes of LFSR data
            for (int i = 0; i < 250; ++i)
            {
                if (ReceiveBit(false, 100) != IterateLFSR())
                    throw new ApplicationException("Receiving LFSR data failed!");
            }

            //Receive pr version
            byte version = 0;
            for (int i = 0; i < 8; ++i)
            {
                version >>= 1;
                version += (byte)(ReceiveBit(false, 100) ? 128 : 0);
            }

            TransmitEncodedLong(command);

            return version;




        }

        #endregion

        #region Low level protocol

        /// <summary>
        /// Receives an encoded bit, if echo on, then constantly writes stuff to serial.
        /// </summary>
        /// <param name="echoOn"></param>
        /// <param name="msecs"></param>
        /// <returns></returns>
        private bool ReceiveBit(bool echoOn, int msecs)
        {
            unchecked
            {

                DateTime entered = System.DateTime.Now;
                while (!echoOn | DateTime.Now - entered < TimeSpan.FromMilliseconds(msecs))
                {
                    if (echoOn)
                    {
                        m_SerialPort.Write(new byte[] { 0xF9 }, 0, 1);  // 0xF9 is 249 in hex
                        Thread.Sleep(25);
                    }
                    if (!echoOn || m_SerialPort.BytesToRead > 0)
                    {
                        byte receivedBit = (byte)(m_SerialPort.ReadByte() - 0xFE); // 0xFE is 254 in hex
                        if (receivedBit > 1)
                        { //Reception error
                            throw new ApplicationException("Receiving bit failed!");
                        }
                        return receivedBit == 1;
                    }
                }
                throw new TimeoutException("Receiving bit in echo mode timed out!");
            }
        }
        /// <summary>
        /// Encodes the long into 11 bytes and transmits it.
        /// </summary>
        /// <param name="data"></param>
        private void TransmitEncodedLong(uint data)
        {
            byte[] buffer = new byte[11];
            for (int i = 0; i < 11; ++i)
            {
                buffer[i] = (byte)(0x92 | ((byte)(i == 10 ? 255 : 0) & 0x60) | (data & 1) | (data & 2) << 2 | (data & 4) << 4);
                data >>= 3;
            }
            m_SerialPort.Write(buffer, 0, 11);
        }
        #endregion

        #region Linear Feedback Shift Register
        private byte _LFSR = 80; //LFSR is initially 80 or ASCII for P  

        /// <summary>
        /// Resets LFSR to 'P'.
        /// </summary>
        private void ResetLFSR()
        {
            _LFSR = 80;
        }

        /// <summary>
        /// Gets a bit from LFSR & advances it by one step.
        /// </summary>
        /// <returns></returns>
        private bool IterateLFSR()
        {
            unchecked
            {
                bool result = (_LFSR & 1) == 1;
                _LFSR = (byte)((_LFSR << 1) | (_LFSR >> 7 ^ _LFSR >> 5 ^ _LFSR >> 4 ^ _LFSR >> 1) & 1);
                return result;
            }
        }
        #endregion


    }
}

AnswerRe: Looking for help deciphering this code class Pin
Richard MacCutchan13-Jan-12 22:23
mveRichard MacCutchan13-Jan-12 22:23 
GeneralRe: Looking for help deciphering this code class Pin
turbosupramk314-Jan-12 3:28
turbosupramk314-Jan-12 3:28 
GeneralRe: Looking for help deciphering this code class Pin
Richard MacCutchan14-Jan-12 3:41
mveRichard MacCutchan14-Jan-12 3:41 
GeneralRe: Looking for help deciphering this code class Pin
harold aptroot14-Jan-12 4:34
harold aptroot14-Jan-12 4:34 
AnswerRe: Looking for help deciphering this code class Pin
OriginalGriff14-Jan-12 0:23
mveOriginalGriff14-Jan-12 0:23 
GeneralRe: Looking for help deciphering this code class Pin
turbosupramk314-Jan-12 3:27
turbosupramk314-Jan-12 3:27 
GeneralRe: Looking for help deciphering this code class Pin
OriginalGriff14-Jan-12 3:37
mveOriginalGriff14-Jan-12 3:37 
GeneralRe: Looking for help deciphering this code class Pin
turbosupramk314-Jan-12 3:41
turbosupramk314-Jan-12 3:41 
GeneralRe: Looking for help deciphering this code class Pin
OriginalGriff14-Jan-12 3:53
mveOriginalGriff14-Jan-12 3:53 
GeneralRe: Looking for help deciphering this code class Pin
harold aptroot14-Jan-12 4:47
harold aptroot14-Jan-12 4:47 
GeneralRe: Looking for help deciphering this code class Pin
OriginalGriff14-Jan-12 5:03
mveOriginalGriff14-Jan-12 5:03 
GeneralRe: Looking for help deciphering this code class Pin
harold aptroot14-Jan-12 5:22
harold aptroot14-Jan-12 5:22 
GeneralRe: Looking for help deciphering this code class Pin
OriginalGriff14-Jan-12 5:31
mveOriginalGriff14-Jan-12 5:31 
GeneralRe: Looking for help deciphering this code class Pin
turbosupramk314-Jan-12 8:18
turbosupramk314-Jan-12 8:18 
GeneralRe: Looking for help deciphering this code class Pin
harold aptroot14-Jan-12 9:34
harold aptroot14-Jan-12 9:34 
GeneralRe: Looking for help deciphering this code class Pin
turbosupramk315-Jan-12 5:23
turbosupramk315-Jan-12 5:23 
AnswerRe: Looking for help deciphering this code class Pin
BobJanova15-Jan-12 23:11
BobJanova15-Jan-12 23:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.