Ejemplo n.º 1
0
        private void UpdateColor()
        {
            // adjust red, green, and blue for brightness
            byte red   = (byte)((double)_red * _brightness);
            byte green = (byte)((double)_green * _brightness);
            byte blue  = (byte)((double)_blue * _brightness);

            int iRetry = 0;

            while (iRetry < 36)
            {
                _writeFrameBuffer[0] = 0x80;
                _writeFrameBuffer[1] = 0x02;  // Module command 'SetColor'
                _writeFrameBuffer[2] = red;   // Red
                _writeFrameBuffer[3] = green; // Green
                _writeFrameBuffer[4] = blue;  // Blue
                _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                _spi.Write(_writeFrameBuffer);

                byte verifyRed, verifyGreen, verifyBlue;
                GetColor(out verifyRed, out verifyGreen, out verifyBlue);

                if (red == verifyRed && green == verifyGreen && blue == verifyBlue)
                {
                    return;
                }

                iRetry++;
            }
        }
Ejemplo n.º 2
0
        //--------
        //-------- Private Methods
        //--------

        /// <summary> Reads the 8 bytes from the scratchpad and verify CRC8 returned.
        ///
        /// </summary>
        /// <param name="data"> buffer to store the scratchpad data
        ///
        /// </param>
        /// <throws>  OneWireIOException on a 1-Wire communication error such as </throws>
        /// <summary>         reading an incorrect CRC from this <code>OneWireContainer10</code>.
        /// This could be caused by a physical interruption in the 1-Wire
        /// Network due to shorts or a newly arriving 1-Wire device issuing a
        /// 'presence pulse'.
        /// </summary>
        /// <throws>  OneWireException on a communication or setup error with the 1-Wire </throws>
        /// <summary>         adapter
        /// </summary>
        private void  readScratch(byte[] data)
        {
            // select the device
            if (adapter.select(address))
            {
                // construct a block to read the scratchpad
                byte[] buffer = new byte[10];

                // read scratchpad command
                buffer[0] = (byte)READ_SCRATCHPAD_COMMAND;

                // now add the read bytes for data bytes and crc8
                for (int i = 1; i < 10; i++)
                {
                    buffer[i] = (byte)SupportClass.Identity(0x0FF);
                }

                // send the block
                adapter.dataBlock(buffer, 0, buffer.Length);

                // see if crc is correct
                if (CRC8.compute(buffer, 1, 9) == 0)
                {
                    Array.Copy(buffer, 1, data, 0, 8);
                }
                else
                {
                    throw new OneWireIOException("OneWireContainer10-Error reading CRC8 from device.");
                }
            }
            else
            {
                throw new OneWireIOException("OneWireContainer10-Device not found on 1-Wire Network");
            }
        }
Ejemplo n.º 3
0
        ICRC getChecker()
        {
            if (CRCType == Helpers.CRCType.None)
            {
                return(null);
            }
            if (cr.ContainsKey(CRCType))
            {
                return(cr[this.CRCType]);
            }
            ICRC toret = null;

            switch (CRCType)
            {
            case Helpers.CRCType.CRC8:
                toret = new CRC8(InitialCrcValue.Zeros);
                break;

            //case Helpers.CRCType.CRC16:
            //    toret = new CRC16(InitialCrcValue.Zeros);
            //    break;
            case Helpers.CRCType.CRC16CCITT:
                toret = new CRC16CCITT(InitialCrcValue.Zeros);
                break;
                //case Helpers.CRCType.CRC32:
                //    toret = new CRC32(InitialCrcValue.Zeros);
                //    break;
            }
            if (toret == null)
            {
                return(null);
            }
            cr.Add(CRCType, toret);
            return(toret);
        }
Ejemplo n.º 4
0
 public static String ComputeCrc8(this byte[] bytes, HashFormat hashFormat)
 {
     using (var hashImpl = new CRC8())
     {
         var hashBytes = hashImpl.ComputeHash(bytes);
         return(ConvertToString(hashBytes, hashFormat));
     }
 }
Ejemplo n.º 5
0
 public static String ComputeCRC8(byte[] bytes)
 {
     using (var hashAlgorithmImpl = new CRC8())
     {
         var hashBytes = hashAlgorithmImpl.ComputeHash(bytes);
         return(String.Concat(hashBytes.Select(b => b.ToString("x2"))));
     }
 }
Ejemplo n.º 6
0
        public double GetValue()
        {
            _writeFrameBuffer[0] = 0x80;
            _writeFrameBuffer[1] = 0x01;  // Module command 'Get ADC value'
            _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
            _spi.Write(_writeFrameBuffer);

            // now, wait for irq to be asserted
            bool responseReceived = false;
            int  numRetries       = 36; //4
            int  iRetry           = 0;

            while (true)
            {
                responseReceived = _irqPortInterruptEvent.WaitOne(10, false);

                if (responseReceived || (iRetry >= numRetries - 1))
                {
                    // parse and return the response
                    _writeFrameBuffer[0] = 0x00; // get data from module
                    _writeFrameBuffer[1] = 0x00;
                    _writeFrameBuffer[2] = 0x00;
                    _writeFrameBuffer[3] = 0x00;
                    _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                    _spi.WriteRead(_writeFrameBuffer, _readFrameBuffer);

                    if (_readFrameBuffer[2] == 2)
                    {
                        // Received two byte ADC value
                        double adcValue = ((short)((_readFrameBuffer[3] << 8) | _readFrameBuffer[4])) / (double)1023;
                        _lastAdcValue = adcValue;
                        return(adcValue);
                    }
                    else if (iRetry >= numRetries - 1)
                    {
                        return(_lastAdcValue);
                    }
                    else
                    {
                        // failed to receive response; retry
                        responseReceived = false;
                    }
                }
                else
                {
                    // TODO: limit our retries to a handful of retries (or maybe a few dozen -- quickly)
                    // retry infinitely
                    _writeFrameBuffer[0] = 0x80;
                    _writeFrameBuffer[1] = 0x01;  // Module command 'Get ADC value'
                    _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                    _spi.Write(_writeFrameBuffer);
                }

                iRetry++;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Puts the address in the front and the correct checksum at the end of the supplied
        /// data array.
        /// </summary>
        /// <param name="data">Data array.</param>
        /// <param name="address">Target device address.</param>
        /// <returns>Complete data frame.</returns>
        private protected byte[] AddAddressAndChecksum(byte[] data, int address)
        {
            byte[] transmitBuffer = new byte[data.Length + 2];
            Array.Copy(data, 0, transmitBuffer, 1, data.Length);

            transmitBuffer[0] = (byte)address;
            transmitBuffer[transmitBuffer.Length - 1] = CRC8.Calculate(transmitBuffer, 0, transmitBuffer.Length - 1);

            return(transmitBuffer);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Checks crc of received frame and returns the data part.
        /// </summary>
        /// <param name="receiveBuffer">Receive buffer.</param>
        /// <returns>Tuple containing the crc status and the data array.</returns>
        private protected (bool, byte[]) CheckCrcAndExtractData(byte[] receiveBuffer)
        {
            if (!CRC8.Check(receiveBuffer, 0, receiveBuffer.Length - 1, receiveBuffer[receiveBuffer.Length - 1]))
            {
                return(false, new byte[0]);
            }

            byte[] receiveBytes = new byte[receiveBuffer.Length - 2];
            Array.Copy(receiveBuffer, 1, receiveBytes, 0, receiveBytes.Length);
            return(true, receiveBytes);
        }
Ejemplo n.º 9
0
        private bool HandleWelcome(byte[] buffer, int length)
        {
            buffReader.SetBuffer(false, buffer, length);

            if (CRC8.ComputeChecksum(0, length - 1, buffReader.ReadBytes(length - 1)) != buffReader.ReadByte())
            {
                return(false);
            }

            buffReader.SetPosition(true, 0);

            MessageTypes msgType = (MessageTypes)buffReader.ReadUInt8();

            if (buffReader.ReadUInt64() != PacketNumber)
            {
                return(false);
            }

            switch (msgType)
            {
            case MessageTypes.Welcome:
                if (CryptoHandleWelcome() == false)
                {
                    return(false);
                }

                if (IsCryptingAccept)                                                                   // Плохой кусок проверки
                {
                    WriteCryptoKeys();
                }
                else
                {
                    IsConnected = true;
                }
                break;

            case MessageTypes.CryptInfo:
                if (CryptoHandleInfo() == false)
                {
                    return(false);
                }
                break;

            default:
                return(false);
            }

            return(true);
        }
Ejemplo n.º 10
0
        private byte[] CheckAndCutCrc(byte[] buffer, string parameterName = null)
        {
            if (buffer.Length != 3)
            {
                throw new ArgumentException("Buffer length must be 3!");
            }
            if (CRC8.ComputeChecksum(buffer) != 0)
            {
                throw new Exception($"CRC error {parameterName} value!");
            }

            return(new byte[2] {
                buffer[1], buffer[0]
            });
        }
Ejemplo n.º 11
0
        //--------
        //-------- Bank specific methods
        //--------

        /// <summary> Reads the 8 byte scratchpad and returns the data in an array.
        ///
        /// </summary>
        /// <param name="none">*
        /// </param>
        /// <returns>  eight byte array that make up the scratchpad
        ///
        /// </returns>
        /// <throws>  OneWireIOException Error reading data </throws>
        /// <throws>  OneWireException Could not find part </throws>
        protected internal virtual byte[] readScratchpad()
        {
            byte[] send_block   = new byte[10];
            byte[] result_block = new byte[8];
            int    crc8;          // this device uses a crc 8

            if (ib.adapter.select(ib.address))
            {
                /* recall memory to the scratchpad */
                //ib.adapter.putByte(RECALL_MEMORY_COMMAND);

                /* perform the read scratchpad */
                //ib.adapter.select(ib.address);

                /* read scratchpad command */
                send_block[0] = (byte)READ_SCRATCHPAD_COMMAND;

                /* now add the read bytes for data bytes and crc8 */
                for (int i = 1; i < 10; i++)
                {
                    send_block[i] = (byte)SupportClass.Identity(0xFF);
                }

                /* send the block */
                ib.adapter.dataBlock(send_block, 0, send_block.Length);

                /*
                 * Now, send_block contains the 8-byte Scratchpad plus READ_SCRATCHPAD_COMMAND byte, and CRC8.
                 * So, convert the block to a 8-byte array representing Scratchpad (get rid of first byte and CRC8)
                 */

                // see if CRC8 is correct
                crc8 = CRC8.compute(send_block, 1, 9);
                if (crc8 != 0)
                {
                    throw new OneWireIOException("Bad CRC during page read " + crc8);
                }

                // copy the data into the result
                Array.Copy(send_block, 1, result_block, 0, 8);

                return(result_block);
            }

            // device must not have been present
            throw new OneWireIOException("Device not found during scratchpad read");
        }
Ejemplo n.º 12
0
        //--------
        //-------- Custom Methods for this iButton Type
        //--------
        //-------------------------------------------------------------------------

        /// <summary>
        /// Reads the Scratchpad of the DS18B20.
        /// </summary>
        /// <returns> 9-byte buffer representing the scratchpad
        /// </returns>
        /// <exception cref="OneWireIOException"> on a 1-Wire communication error such as
        ///         reading an incorrect CRC from this <code>OneWireContainer28</code>.
        ///         This could be caused by a physical interruption in the 1-Wire
        ///         Network due to shorts or a newly arriving 1-Wire device issuing a
        ///         'presence pulse'. </exception>
        /// <exception cref="OneWireException"> on a communication or setup error with the 1-Wire
        ///         adapter </exception>
        public virtual byte[] readScratchpad()
        {
            byte[] result_block;

            // select the device
            if (adapter.select(address))
            {
                // create a block to send that reads the scratchpad
                byte[] send_block = new byte[10];

                // read scratchpad command
                send_block[0] = (byte)READ_SCRATCHPAD_COMMAND;

                // now add the read bytes for data bytes and crc8
                for (int i = 1; i < 10; i++)
                {
                    send_block[i] = unchecked ((byte)0xFF);
                }

                // send the block
                adapter.dataBlock(send_block, 0, send_block.Length);

                // now, send_block contains the 9-byte Scratchpad plus READ_SCRATCHPAD_COMMAND byte
                // convert the block to a 9-byte array representing Scratchpad (get rid of first byte)
                result_block = new byte[9];

                for (int i = 0; i < 9; i++)
                {
                    result_block[i] = send_block[i + 1];
                }

                // see if CRC8 is correct
                if (CRC8.compute(send_block, 1, 9) == 0)
                {
                    return(result_block);
                }
                else
                {
                    throw new OneWireIOException("OneWireContainer28-Error reading CRC8 from device.");
                }
            }

            // device must not have been present
            throw new OneWireIOException("OneWireContainer28-Device not found on 1-Wire Network");
        }
Ejemplo n.º 13
0
        //--------
        //-------- Bank specific methods
        //--------

        /// <summary>
        /// Reads the specified 8 byte page and returns the data in an array.
        /// </summary>
        /// <param name="page"> the page number to read
        /// </param>
        /// <returns>  eight byte array that make up the page
        /// </returns>
        /// <exception cref="OneWireIOException"> Error reading data </exception>
        /// <exception cref="OneWireException"> Could not find part </exception>
        /// <exception cref="IllegalArgumentException"> Bad parameters passed </exception>
        protected internal virtual byte[] readRawPage(int page)
        {
            byte[] buffer = new byte[11];
            byte[] result = new byte[8];
            int    crc8; // this device uses a crc 8

            if (ib.adapter.select(ib.address))
            {
                /* recall memory to the scratchpad */
                buffer[0] = RECALL_MEMORY_COMMAND;
                buffer[1] = (byte)page;

                ib.adapter.dataBlock(buffer, 0, 2);

                /* perform the read scratchpad */
                ib.adapter.select(ib.address);

                buffer[0] = READ_SCRATCHPAD_COMMAND;
                buffer[1] = (byte)page;

                for (int i = 2; i < 11; i++)
                {
                    buffer[i] = unchecked ((byte)0x0ff);
                }

                ib.adapter.dataBlock(buffer, 0, 11);

                /* do the crc check */
                crc8 = CRC8.compute(buffer, 2, 9);

                if (crc8 != 0x0)
                {
                    throw new OneWireIOException("Bad CRC during page read " + crc8);
                }

                // copy the data into the result
                Array.Copy(buffer, 2, result, 0, 8);
            }
            else
            {
                throw new OneWireIOException("Device not found during read page.");
            }

            return(result);
        }
Ejemplo n.º 14
0
        /// <summary> Retrieves this <code>OneWireContainer10</code> state information.
        /// The state information is returned as a byte array.  Pass this byte
        /// array to the '<code>get</code>' and '<code>set</code>' methods.
        /// If the device state needs to be changed, then call the
        /// <code>writeDevice()</code> to finalize the changes.
        ///
        /// </summary>
        /// <returns> <code>OneWireContainer10</code> state information.
        /// Device state looks like this:
        /// <pre>
        /// 0 : temperature LSB
        /// 1 : temperature MSB
        /// 2 : trip high
        /// 3 : trip low
        /// 4 : reserved (put the resolution here, 0 for normal, 1 for max)
        /// 5 : reserved
        /// 6 : count remain
        /// 7 : count per degree Celsius
        /// 8 : an 8 bit CRC over the previous 8 bytes of data
        /// </pre>
        ///
        /// </returns>
        /// <throws>  OneWireIOException on a 1-Wire communication error such as </throws>
        /// <summary>         reading an incorrect CRC from this <code>OneWireContainer10</code>.
        /// This could be caused by a physical interruption in the 1-Wire
        /// Network due to shorts or a newly arriving 1-Wire device issuing a
        /// 'presence pulse'.
        /// </summary>
        /// <throws>  OneWireException on a communication or setup error with the 1-Wire </throws>
        /// <summary>         adapter
        ///
        /// </summary>
        /// <seealso cref="writeDevice">
        /// </seealso>
        public virtual byte[] readDevice()
        {
            byte[] data = new byte[8];

            doSpeed();

            // select the device
            if (adapter.select(address))
            {
                // construct a block to read the scratchpad
                byte[] buffer = new byte[10];

                // read scratchpad command
                buffer[0] = (byte)READ_SCRATCHPAD_COMMAND;

                // now add the read bytes for data bytes and crc8
                for (int i = 1; i < 10; i++)
                {
                    buffer[i] = (byte)SupportClass.Identity(0x0FF);
                }

                // send the block
                adapter.dataBlock(buffer, 0, buffer.Length);

                // see if crc is correct
                if (CRC8.compute(buffer, 1, 9) == 0)
                {
                    Array.Copy(buffer, 1, data, 0, 8);
                }
                else
                {
                    throw new OneWireIOException("OneWireContainer10-Error reading CRC8 from device.");
                }
            }
            else
            {
                throw new OneWireIOException("OneWireContainer10-Device not found on 1-Wire Network");
            }

            //we are just reading normalResolution here, no need to synchronize
            data[4] = (byte)(normalResolution?0:1);

            return(data);
        }
Ejemplo n.º 15
0
        public void SetFrequency(double frequency)
        {
            byte frequencyHighByte;
            byte frequencyLowByte;

            if (frequency <= 0)
            {
                frequencyHighByte = 0;
                frequencyLowByte  = 0;
            }
            else
            {
                // The Piezo Buzzer module time base is 1000 kHz
                int divider = (int)(1000000F / frequency + 0.5);

                // The data sent to module is direct value for the TIM2 ARRH, ARRL
                // registers, to save expensive division on STM8S.
                frequencyHighByte = (byte)(divider >> 8);  // ARRH
                frequencyLowByte  = (byte)(divider);       // ARRL
            }

            int iRetry = 0;

            while (iRetry < 36)
            {
                _writeFrameBuffer[0] = 0x80;
                _writeFrameBuffer[1] = 0x02;  // Module command 'SetColor'
                _writeFrameBuffer[2] = frequencyHighByte;
                _writeFrameBuffer[3] = frequencyLowByte;
                _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                _spi.Write(_writeFrameBuffer);

                double verifyFrequency;
                GetFrequency(out verifyFrequency);

                if (frequency - verifyFrequency <= 100)
                {
                    return;
                }

                iRetry++;
            }
        }
Ejemplo n.º 16
0
        /**
         * Constructor of DataCode
         *
         * @param u8    the character to be transformed
         * @param index the index of the char
         */
        public DataCode(char u8, int index)
        {
            if (index > INDEX_MAX)
            {
                throw new EsptouchException("index > INDEX_MAX");
            }
            byte[] dataBytes = ByteUtil.splitUint8To2bytes(u8);
            mDataHigh = dataBytes[0];
            mDataLow  = dataBytes[1];

            CRC8 crc8 = new CRC8();

            crc8.update(ByteUtil.convertUint8toByte(u8));
            crc8.update(index);

            byte[] crcBytes = ByteUtil.splitUint8To2bytes((char)crc8.getValue());
            mCrcHigh   = crcBytes[0];
            mCrcLow    = crcBytes[1];
            mSeqHeader = (byte)index;
        }
Ejemplo n.º 17
0
        public byte[] ReadScratchpad()
        {
            byte[] result_block;

            // select the device
            if (Adapter.SelectDevice(Address, 0))
            {
                // create a block to send that reads the scratchpad
                byte[] send_block = new byte[10];

                // read scratchpad command
                send_block[0] = (byte)0xBE;

                // now add the read bytes for data bytes and crc8
                for (int i = 1; i < 10; i++)
                {
                    send_block[i] = (byte)0xFF;
                }

                // send the block
                //Adapter.DataBlock(send_block, 0, send_block.Length);
                Adapter.DataBlock(send_block);

                // now, send_block contains the 9-byte Scratchpad plus READ_SCRATCHPAD_COMMAND byte
                // convert the block to a 9-byte array representing Scratchpad (get rid of first byte)
                result_block = new byte[9];

                for (int i = 0; i < 9; i++)
                {
                    result_block[i] = send_block[i + 1];
                }

                // see if CRC8 is correct
                if (CRC8.Compute(send_block, 1, 9) == 0)
                {
                    return(result_block);
                }
            }

            return(null);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Read bytes from the device
        /// </summary>
        /// <param name="offset">Location or address in the device</param>
        /// <param name="length">Number of bytes to read</param>
        /// <param name="ok">A ref to a bool that indicates success</param>
        /// <returns>An array of bytes read from the device</returns>
        private static byte[] Read(int offset, int length, out bool ok)
        {
            var response = new byte[length];
            var answer = new byte[133];

            bool nak = false;

            var loop = length / 128;
            if ((length % 128) > 0)
            {
                loop++;
            }

            int read = 0;
            byte nb = 128;
            int badDataRetryCount = 0;
            bool badData = false;

            do /* Each 128 byte (max) frame */
            {
                do /* Retry up to BAD_DATA_RETRIES times when bad data is read */
                {
                    badData = false;

                    if ((length - read) < 128)
                    {
                        nb = (byte)(length - read);
                    }

                    var offsetBytes = BitConverter.GetBytes(offset);
                    request[4] = offsetBytes[0];
                    request[5] = offsetBytes[1];
                    request[6] = offsetBytes[2];
                    request[7] = offsetBytes[3];
                    request[8] = nb;
                    request[9] = crc.Calculate(request.Skip(3).Take(6).ToArray());
                    vcp.Write(request, 0, 11);

                    int r = 0;
                    try
                    {
                        while ((r += vcp.Read(answer, r, nb + 5 - r)) < nb + 5)
                        {
                            /* Read into answer until full chunk is recieved */
                        }
                    }
                    catch
                    {
                        /* Typically timeout*/
                        nak = true;
                    }

                    if (r > 0)
                    {
                        /* Error checking */

                        /* Device said NAK */
                        if (answer[r - 1] == NAK)
                        {
                            nak = true;
                            break;
                        }

                        /* Check for device ACK */
                        if (answer[nb + 4] != ACK)
                        {
                            badData = true;
                        }

                        /* STX header */
                        if (answer[0] != STX)
                        {
                            badData = true;
                        }

                        /* MsgID header */
                        if (answer[1] != MSG_ID_GET_LOG)
                        {
                            badData = true;
                        }

                        /* Number of bytes read matches request */
                        if (answer[2] != nb)
                        {
                            badData = true;
                        }

                        /* CRC */
                        CRC8 frameCrc = new CRC8(0x8c);
                        byte crcVal = frameCrc.Calculate(answer.Skip(3).Take(nb).ToArray());
                        if (answer[nb + 3] != crcVal)
                        {
                            badData = true;
                        }
                    }

                    if (nak == true)
                    {
                        break;
                    }

                    if (badData)
                    {
                        badDataRetryCount++;
                    }
                    else
                    {
                        Array.Copy(answer, 3, response, read, nb);
                        offset += nb;
                        read += nb;
                    }
                }
                while (badData && badDataRetryCount < BAD_DATA_RETRIES);

                if (badData)
                {
                    /* If we still had bad data after BAD_DATA_RETRIES then give up with NAK
                     * Read() function will be called once more externally on NAK (ok = false)
                     */
                    nak = true;
                    break;
                }
            }
            while (--loop > 0);  /* Next 128 byte frame */

            ok = !nak;
            return response;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Writes a page of memory to this device. Pages 3-6 are always
        /// available for user storage and page 7 is available if the CA bit is set
        /// to 0 (false) with <CODE>setFlag()</CODE>.
        /// </summary>
        /// <param name="page">    the page number </param>
        /// <param name="source">  data to be written to page </param>
        /// <param name="offset">  offset with page to begin writting
        ///
        /// @returns 'true' if the write was successfull
        /// </param>
        /// <exception cref="OneWireIOException"> Error reading data </exception>
        /// <exception cref="OneWireException"> Could not find part </exception>
        /// <exception cref="IllegalArgumentException"> Bad parameters passed </exception>
        protected internal virtual void writeRawPage(int page, byte[] source, int offset)
        {
            byte[] buffer = new byte[12];
            int    crc8;

            if (ib.adapter.select(ib.address))
            {
                // write the page to the scratchpad first
                buffer[0] = WRITE_SCRATCHPAD_COMMAND;
                buffer[1] = (byte)page;

                Array.Copy(source, offset, buffer, 2, 8);
                ib.adapter.dataBlock(buffer, 0, 10);

                // read back the scrathpad
                if (ib.adapter.select(ib.address))
                {
                    // write the page to the scratchpad first
                    buffer[0] = READ_SCRATCHPAD_COMMAND;
                    buffer[1] = (byte)page;

                    Array.Copy(ffBlock, 0, buffer, 2, 9);
                    ib.adapter.dataBlock(buffer, 0, 11);

                    /* do the crc check */
                    crc8 = CRC8.compute(buffer, 2, 9);

                    if (crc8 != 0x0)
                    {
                        throw new OneWireIOException("Bad CRC during scratchpad read " + crc8);
                    }

                    // now copy that part of the scratchpad to memory
                    if (ib.adapter.select(ib.address))
                    {
                        buffer[0] = COPY_SCRATCHPAD_COMMAND;
                        buffer[1] = (byte)page;

                        ib.adapter.dataBlock(buffer, 0, 2);

                        // give it some time to write
                        try
                        {
                            Thread.Sleep(12);
                        }
                        catch (InterruptedException)
                        {
                        }

                        // check the result
                        if ((byte)ib.adapter.Byte != unchecked ((byte)0xFF))
                        {
                            throw new OneWireIOException("Copy scratchpad verification not found.");
                        }

                        return;
                    }
                }
            }

            throw new OneWireIOException("Device not found during write page.");
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Syncronously reads data from the BioHarness.
        /// Handles the maximum message size constraints, splitting the
        /// request into manageable chunks, and reassembling the response.
        /// </summary>
        /// <param name="offset">The byte to start read at</param>
        /// <param name="length">The number of bytes to read</param>        
        /// <returns>A byte array conaining the requested data</returns>
        private static byte[] SyncRead(int offset, int length)
        {
            CRC8 crc = new CRC8(0x8c);
            var response = new byte[length];
            var answer = new byte[133];
            /* request = STX, MSG_ID_LOG,  DLC, ... ETX */
            byte[] request = new byte[] { STX, MSG_ID_GET_LOG, DLC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ETX };

            var loop = length / 128;
            if ((length % 128) > 0)
            {
                loop++;
            }

            int read = 0;
            byte nb = 128;
            do
            {
                if ((length - read) < 128)
                {
                    nb = (byte)(length - read);
                }

                var offsetBytes = BitConverter.GetBytes(offset);
                request[4] = offsetBytes[0];
                request[5] = offsetBytes[1];
                request[6] = offsetBytes[2];
                request[7] = offsetBytes[3];
                request[8] = nb;
                request[9] = crc.Calculate(request.Skip(3).Take(6).ToArray());

                vcp.Write(request, 0, 11);

                int r = 0;
                while ((r += vcp.Read(answer, r, nb + 5 - r)) < nb + 5)
                {
                }

                Array.Copy(answer, 3, response, read, nb);
                offset += nb;
                read += nb;
            }
            while (--loop > 0);

            return response;
        }
Ejemplo n.º 21
0
            static Dictionary <string, byte[][]> dataTemp = new Dictionary <string, byte[][]>(); //存储临时数据包数据,用于重发

            /// <summary>
            /// 获取分片udp数据集合
            /// </summary>
            /// <param name="source">原数据包</param>
            /// <param name="blockSize">块大小</param>
            /// <returns></returns>
            public static List <byte[]> DataFragme(byte[] source, int blockSize = 50000)
            {
                List <byte[]> list = new List <byte[]>();
                string        key  = DateTime.Now.ToString("yyyyMMddhhmmssff");//单任务唯一标识

                byte[] keyBuff = Encoding.UTF8.GetBytes(key);
                int    bls     = source.Length / blockSize;

                //计算包个数
                if (source.Length % blockSize != 0)
                {
                    bls++;
                }
                byte[] blocks = BitConverter.GetBytes(bls);
                byte[] id     = BitConverter.GetBytes(0);


                //报头序列约定:单任务标识,id,包分组数

                byte[] headBuff = new byte[24];
                keyBuff.CopyTo(headBuff, 0);
                id.CopyTo(headBuff, 16);
                blocks.CopyTo(headBuff, 20);

                list.Add(headBuff);

                if (source.Length < blockSize)
                {
                    id = BitConverter.GetBytes(1);//该包编号
                    byte[] len      = BitConverter.GetBytes(source.Length + 1);
                    byte[] overBuff = new byte[source.Length + 25];
                    keyBuff.CopyTo(overBuff, 0);
                    id.CopyTo(overBuff, keyBuff.Length);
                    len.CopyTo(overBuff, keyBuff.Length + id.Length);
                    source.CopyTo(overBuff, 24);
                    byte crc = CRC8.CRC(source);
                    overBuff[overBuff.Length - 1] = crc;
                    list.Add(overBuff);
                    return(list);
                }

                //子报头序列约定:单任务标识,id,子包有效数据长度
                int block = 0;

                for (int i = 1; block != source.Length; i++)
                {
                    byte[] bys = source.Take(block + blockSize).Skip(block).ToArray(); //当次分块数据
                    block += bys.Length;
                    id     = BitConverter.GetBytes(i);                                 //该包编号
                    byte[] len      = BitConverter.GetBytes(bys.Length + 1);           //包长度
                    byte[] overBuff = new byte[bys.Length + 25];

                    //CRC校验位附加
                    byte   crc  = CRC8.CRC(bys);
                    byte[] temp = new byte[bys.Length + 1];
                    bys.CopyTo(temp, 0);
                    temp[temp.Length - 1] = crc;
                    bys = temp;

                    keyBuff.CopyTo(overBuff, 0);
                    id.CopyTo(overBuff, keyBuff.Length);
                    len.CopyTo(overBuff, keyBuff.Length + id.Length);
                    bys.CopyTo(overBuff, 24);

                    list.Add(overBuff);
                }
                if (!dataTemp.ContainsKey(key))
                {
                    dataTemp.Add(key, list.ToArray());
                }
                StartWaitRequest(key);
                return(list);
            }
Ejemplo n.º 22
0
		/// <summary> Program an EPROM byte at the specified address.
		/// 
		/// </summary>
		/// <param name="addr">         address
		/// </param>
		/// <param name="data">         data byte to program
		/// </param>
		/// <param name="writeContinue">if 'true' then device programming is continued without
		/// re-selecting.  This can only be used if the new
		/// programByte() continious where the last one
		/// stopped and it is inside a
		/// 'beginExclusive/endExclusive' block.
		/// 
		/// </param>
		/// <returns>  the echo byte after programming.  This should be the desired
		/// byte to program if the location was previously unprogrammed.
		/// 
		/// </returns>
		/// <throws>  OneWireIOException </throws>
		/// <throws>  OneWireException </throws>
		protected internal virtual byte programByte(int addr, byte data, bool writeContinue)
		{
			int lastcrc = 0, len;
			
			if (!writeContinue)
			{
				
				// select the device
				if (!ib.adapter.select(ib.address))
				{
					forceVerify();
					
					throw new OneWireIOException("device not present");
				}
				
				// pre-fill with 0xFF 
				byte[] raw_buf = new byte[6];
				
				Array.Copy(ffBlock, 0, raw_buf, 0, raw_buf.Length);
				
				// contruct packet
				raw_buf[0] = (byte) WRITE_MEMORY_COMMAND;
				raw_buf[1] = (byte) (addr & 0xFF);
				raw_buf[2] = (byte) ((SupportClass.URShift((addr & 0xFFFF), 8)) & 0xFF);
				raw_buf[3] = (byte) data;
				
				if (numCRCBytes == 2)
				{
					lastcrc = CRC16.compute(raw_buf, 0, 4, 0);
					len = 6;
				}
				else
				{
					lastcrc = CRC8.compute(raw_buf, 0, 4, 0);
					len = 5;
				}
				
				// send block to read data + crc
				ib.adapter.dataBlock(raw_buf, 0, len);
				
				// check CRC
				if (numCRCBytes == 2)
				{
					if (CRC16.compute(raw_buf, 4, 2, lastcrc) != 0x0000B001)
					{
						forceVerify();
						
						throw new OneWireIOException("Invalid CRC16 read from device");
					}
				}
				else
				{
					if (CRC8.compute(raw_buf, 4, 1, lastcrc) != 0)
					{
						forceVerify();
						
						throw new OneWireIOException("Invalid CRC8 read from device");
					}
				}
			}
			else
			{
				
				// send the data
				ib.adapter.putByte(data);
				
				// check CRC from device
				if (numCRCBytes == 2)
				{
					lastcrc = CRC16.compute(data, addr);
					lastcrc = CRC16.compute(ib.adapter.Byte, lastcrc);
					
					if (CRC16.compute(ib.adapter.Byte, lastcrc) != 0x0000B001)
					{
						forceVerify();
						
						throw new OneWireIOException("Invalid CRC16 read from device");
					}
				}
				else
				{
					lastcrc = CRC8.compute(data, addr);
					
					if (CRC8.compute(ib.adapter.Byte, lastcrc) != 0)
					{
						forceVerify();
						
						throw new OneWireIOException("Invalid CRC8 read from device");
					}
				}
			}
			
			// send the pulse 
			ib.adapter.startProgramPulse(DSPortAdapter.CONDITION_NOW);
			
			// return the result
			return (byte) ib.adapter.Byte;
		}
Ejemplo n.º 23
0
        /// <summary> Writes a page of memory to this device. Pages 3-6 are always
        /// available for user storage and page 7 is available if the CA bit is set
        /// to 0 (false) with <CODE>setFlag()</CODE>.
        ///
        /// </summary>
        /// <param name="page">   the page number
        /// </param>
        /// <param name="source"> data to be written to page
        /// </param>
        /// <param name="offset"> offset with page to begin writting
        ///
        /// </param>
        /// <returns>s 'true' if the write was successfull
        ///
        /// </returns>
        /// <throws>  OneWireIOException Error reading data </throws>
        /// <throws>  OneWireException Could not find part </throws>
        /// <throws>  IllegalArgumentException Bad parameters passed </throws>
        protected internal virtual void  writeRawPage(int page, byte[] source, int offset)
        {
            byte[] buffer = new byte[12];
            int    crc8;

            if (ib.adapter.select(ib.address))
            {
                // write the page to the scratchpad first
                buffer[0] = WRITE_SCRATCHPAD_COMMAND;
                buffer[1] = (byte)page;

                Array.Copy(source, offset, buffer, 2, 8);
                ib.adapter.dataBlock(buffer, 0, 10);

                // read back the scrathpad
                if (ib.adapter.select(ib.address))
                {
                    // write the page to the scratchpad first
                    buffer[0] = READ_SCRATCHPAD_COMMAND;
                    buffer[1] = (byte)page;

                    Array.Copy(ffBlock, 0, buffer, 2, 9);
                    ib.adapter.dataBlock(buffer, 0, 11);

                    /* do the crc check */
                    crc8 = CRC8.compute(buffer, 2, 9);

                    if (crc8 != 0x0)
                    {
                        throw new OneWireIOException("Bad CRC during scratchpad read " + crc8);
                    }

                    // now copy that part of the scratchpad to memory
                    if (ib.adapter.select(ib.address))
                    {
                        buffer[0] = COPY_SCRATCHPAD_COMMAND;
                        buffer[1] = (byte)page;

                        ib.adapter.dataBlock(buffer, 0, 2);

                        // give it some time to write
                        try
                        {
                            //UPGRADE_TODO: Method 'java.lang.Thread.sleep' was converted to 'System.Threading.Thread.Sleep' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangThreadsleep_long'"
                            System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 12));
                        }
                        catch (System.Threading.ThreadInterruptedException e)
                        {
                        }

                        // check the result
                        if ((byte)ib.adapter.Byte != (byte)SupportClass.Identity(0xFF))
                        {
                            throw new OneWireIOException("Copy scratchpad verification not found.");
                        }

                        return;
                    }
                }
            }

            throw new OneWireIOException("Device not found during write page.");
        }
Ejemplo n.º 24
0
        /**
         * Constructor of DatumCode
         *
         * @param apSsid      the Ap's ssid
         * @param apBssid     the Ap's bssid
         * @param apPassword  the Ap's password
         * @param ipAddress   the ip address of the phone or pad
         * @param encryptor null use origin data, not null use encrypted data
         */
        public DatumCode(byte[] apSsid, byte[] apBssid, byte[] apPassword,
                         IPAddress ipAddress, ITouchEncryptor encryptor)
        {
            // Data = total len(1 byte) + apPwd len(1 byte) + SSID CRC(1 byte) +
            // BSSID CRC(1 byte) + TOTAL XOR(1 byte)+ ipAddress(4 byte) + apPwd + apSsid apPwdLen <=
            // 105 at the moment

            // total xor
            char totalXor = (char)0;

            char apPwdLen = (char)apPassword.Length;
            CRC8 crc      = new CRC8();

            crc.update(apSsid);
            char apSsidCrc = (char)crc.getValue();

            crc.reset();
            crc.update(apBssid);
            char apBssidCrc = (char)crc.getValue();

            char apSsidLen = (char)apSsid.Length;

            byte[] ipBytes = ipAddress.GetAddressBytes();
            int    ipLen   = ipBytes.Length;

            char totalLen = (char)(EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen);

            // build data codes
            mDataCodes = new List <DataCode>();
            mDataCodes.Add(new DataCode(totalLen, 0));
            totalXor ^= totalLen;
            mDataCodes.Add(new DataCode(apPwdLen, 1));
            totalXor ^= apPwdLen;
            mDataCodes.Add(new DataCode(apSsidCrc, 2));
            totalXor ^= apSsidCrc;
            mDataCodes.Add(new DataCode(apBssidCrc, 3));
            totalXor ^= apBssidCrc;
            // ESPDataCode 4 is null
            for (int i = 0; i < ipLen; ++i)
            {
                char c = ByteUtil.convertByte2Uint8(ipBytes[i]);
                totalXor ^= c;
                mDataCodes.Add(new DataCode(c, i + EXTRA_HEAD_LEN));
            }

            for (int i = 0; i < apPassword.Length; i++)
            {
                char c = ByteUtil.convertByte2Uint8(apPassword[i]);
                totalXor ^= c;
                mDataCodes.Add(new DataCode(c, i + EXTRA_HEAD_LEN + ipLen));
            }

            // totalXor will xor apSsidChars no matter whether the ssid is hidden
            for (int i = 0; i < apSsid.Length; i++)
            {
                char c = ByteUtil.convertByte2Uint8(apSsid[i]);
                totalXor ^= c;
                mDataCodes.Add(new DataCode(c, i + EXTRA_HEAD_LEN + ipLen + apPwdLen));
            }

            // add total xor last
            mDataCodes.Insert(4, new DataCode(totalXor, 4));

            // add bssid
            int bssidInsertIndex = EXTRA_HEAD_LEN;

            for (int i = 0; i < apBssid.Length; i++)
            {
                int      index = totalLen + i;
                char     c     = ByteUtil.convertByte2Uint8(apBssid[i]);
                DataCode dc    = new DataCode(c, index);
                if (bssidInsertIndex >= mDataCodes.Count)
                {
                    mDataCodes.Add(dc);
                }
                else
                {
                    mDataCodes.Insert(bssidInsertIndex, dc);
                }
                bssidInsertIndex += 4;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Read bytes from the USB device
        /// </summary>
        /// <param name="offset">Location into the file (address in device)</param>
        /// <param name="length">Number of bytes to read</param>
        /// <param name="ok">Boolean indicating whether the read was successfull</param>
        /// <returns>An array of bytes read from the device</returns>
        private static byte[] ReadUsb(int offset, int length, out bool ok)
        {
            var response = new byte[length];
            var answer   = new byte[133];

            bool nak = false;

            var loop = length / 128;

            if ((length % 128) > 0)
            {
                loop++;
            }

            int  read = 0;
            byte nb   = 128;
            int  badDataRetryCount = 0;
            bool badData           = false;

            do /* Each 128 byte (max) frame */
            {
                badDataRetryCount = 0;
                do /* Retry up to BAD_DATA_RETRIES times when bad data is read */
                {
                    numRequests++;
                    badData = false;

                    if ((length - read) < 128)
                    {
                        nb = (byte)(length - read);
                    }

                    var offsetBytes = BitConverter.GetBytes(offset);
                    request[4] = offsetBytes[0];
                    request[5] = offsetBytes[1];
                    request[6] = offsetBytes[2];
                    request[7] = offsetBytes[3];
                    request[8] = nb;
                    request[9] = crc.Calculate(request.Skip(3).Take(6).ToArray());
                    winUsbDevice.Write(request, 11);

                    DateTime timeout = DateTime.Now;

                    int r = 0;
                    try
                    {
                        while ((r += winUsbDevice.Read(answer, r, nb + 5 - r)) < nb + 5)
                        {
                            /* Read into answer until full chunk is recieved */
                            System.Threading.Thread.Sleep(0);

                            /*
                             * XXX: TODO:
                             * On ZModem that does not support 0x02 log message
                             * When operating via USB this returns a NAK
                             * then ends up in an infinate loop.
                             * WONT affect commercial products (ZModem is serial not USB)
                             */
                            if ((DateTime.Now - timeout) > TimeSpan.FromMilliseconds(2000))
                            {
                                System.Diagnostics.Debug.WriteLine(string.Format("Error : Timeout - {0}.", offset));
                                break;
                            }
                        }
                    }
                    catch
                    {
                        /* Typically timeout */
                        nak     = true;
                        badData = true;
                    }

                    if (r > 0)
                    {
                        /* Error checking */

                        /* Device said NAK */
                        if (answer[r - 1] == NAK)
                        {
                            badData = true; /* nak = true; */
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : NAK - {0}.", offset));
                        }

                        /* Check for device ACK */
                        if (answer[nb + 4] != ACK)
                        {
                            badData = true;
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : Not ACK - {0}.", offset));
                        }

                        /* STX header */
                        if (answer[0] != STX)
                        {
                            badSTXCount++;
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : Not STX - {0}.", offset));
                            badData = true;
                        }

                        /* MsgID header */
                        if (answer[1] != MSG_ID_GET_LOG)
                        {
                            badMsgCount++;
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : Wrong Msg ID - {0}.", offset));
                            badData = true;
                        }

                        /* Number of bytes read matches request */
                        if (answer[2] != nb)
                        {
                            badBytesReadCount++;
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : Wrong number of bytes - {0}.", offset));
                            badData = true;
                        }

                        /* CRC */
                        CRC8 frameCrc = new CRC8(0x8c);
                        byte crcVal   = frameCrc.Calculate(answer.Skip(3).Take(nb).ToArray());
                        if (answer[nb + 3] != crcVal)
                        {
                            badCRCCount++;
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : Wrong CRC - {0}.", offset));
                            badData = true;
                        }
                    }

                    if (nak == true)
                    {
                        break;
                    }

                    if (badData)
                    {
                        badDataRetryCount++;
                        var byteToRead = winUsbDevice.BytesToRead;
                        if (byteToRead > 0)
                        {
                            System.Diagnostics.Debug.WriteLine(string.Format("Error : Flush the buffer of {1} bytes - {0}.", offset, byteToRead));
                            winUsbDevice.Read(new byte[byteToRead]);
                        }
                    }
                    else
                    {
                        if (r > 0)
                        {
                            Array.Copy(answer, 3, response, read, nb);
                            offset += nb;
                            read   += nb;
                        }
                        else
                        {
                            badData = true;
                        }
                    }
                }while (badData && (badDataRetryCount < BAD_DATA_RETRIES));

                if (badData)
                {
                    /*
                     * If we still had bad data after BAD_DATA_RETRIES then give up with NAK
                     * Read() function will be called once more externally on NAK (ok = false)
                     */
                    nak = true;
                    break;
                }
            }while (--loop > 0);  /* Next 128 byte frame */

            ok = !nak;
            return(response);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Read bytes from the device
        /// </summary>
        /// <param name="offset">Location or address in the device</param>
        /// <param name="length">Number of bytes to read</param>
        /// <param name="ok">A ref to a bool that indicates success</param>
        /// <returns>An array of bytes read from the device</returns>
        private static byte[] Read(int offset, int length, out bool ok)
        {
            if (!isSerial)
            {
                return(ReadUsb(offset, length, out ok));
            }

            var response = new byte[length];
            var answer   = new byte[133];

            bool nak = false;

            var loop = length / 128;

            if ((length % 128) > 0)
            {
                loop++;
            }

            int  read = 0;
            byte nb   = 128;
            int  badDataRetryCount = 0;
            bool badData           = false;

            do     /* Each 128 byte (max) frame */
            {
                do /* Retry up to BAD_DATA_RETRIES times when bad data is read */
                {
                    badData = false;

                    if ((length - read) < 128)
                    {
                        nb = (byte)(length - read);
                    }

                    var offsetBytes = BitConverter.GetBytes(offset);
                    request[4] = offsetBytes[0];
                    request[5] = offsetBytes[1];
                    request[6] = offsetBytes[2];
                    request[7] = offsetBytes[3];
                    request[8] = nb;
                    request[9] = crc.Calculate(request.Skip(3).Take(6).ToArray());
                    vcp.Write(request, 0, 11);

                    int r = 0;
                    try
                    {
                        while ((r += vcp.Read(answer, r, nb + 5 - r)) < nb + 5)
                        {
                            /* Read into answer until full chunk is recieved */
                        }
                    }
                    catch
                    {
                        /* Typically timeout*/
                        nak = true;
                    }

                    if (r > 0)
                    {
                        /* Error checking */

                        /* Device said NAK */
                        if (answer[r - 1] == NAK)
                        {
                            nak = true;
                            break;
                        }

                        /* Check for device ACK */
                        if (answer[nb + 4] != ACK)
                        {
                            badData = true;
                        }

                        /* STX header */
                        if (answer[0] != STX)
                        {
                            badData = true;
                        }

                        /* MsgID header */
                        if (answer[1] != MSG_ID_GET_LOG)
                        {
                            badData = true;
                        }

                        /* Number of bytes read matches request */
                        if (answer[2] != nb)
                        {
                            badData = true;
                        }

                        /* CRC */
                        CRC8 frameCrc = new CRC8(0x8c);
                        byte crcVal   = frameCrc.Calculate(answer.Skip(3).Take(nb).ToArray());
                        if (answer[nb + 3] != crcVal)
                        {
                            badData = true;
                        }
                    }

                    if (nak == true)
                    {
                        break;
                    }

                    if (badData)
                    {
                        badDataRetryCount++;
                    }
                    else
                    {
                        Array.Copy(answer, 3, response, read, nb);
                        offset += nb;
                        read   += nb;
                    }
                }while (badData && badDataRetryCount < BAD_DATA_RETRIES);

                if (badData)
                {
                    /* If we still had bad data after BAD_DATA_RETRIES then give up with NAK
                     * Read() function will be called once more externally on NAK (ok = false)
                     */
                    nak = true;
                    break;
                }
            }while (--loop > 0);  /* Next 128 byte frame */

            ok = !nak;
            return(response);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Syncronously reads data from the BioHarness.
        /// Handles the maximum message size constraints, splitting the
        /// request into manageable chunks, and reassembling the response.
        /// </summary>
        /// <param name="offset">The byte to start read at</param>
        /// <param name="length">The number of bytes to read</param>
        /// <returns>A byte array conaining the requested data</returns>
        private static byte[] SyncRead(int offset, int length)
        {
            CRC8 crc      = new CRC8(0x8c);
            var  response = new byte[length];
            var  answer   = new byte[133];

            /* request = STX, MSG_ID_LOG,  DLC, ... ETX */
            byte[] request = new byte[] { STX, MSG_ID_GET_LOG, DLC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ETX };

            var loop = length / 128;

            if ((length % 128) > 0)
            {
                loop++;
            }

            int  read = 0;
            byte nb   = 128;

            do
            {
                if ((length - read) < 128)
                {
                    nb = (byte)(length - read);
                }

                var offsetBytes = BitConverter.GetBytes(offset);
                request[4] = offsetBytes[0];
                request[5] = offsetBytes[1];
                request[6] = offsetBytes[2];
                request[7] = offsetBytes[3];
                request[8] = nb;
                request[9] = crc.Calculate(request.Skip(3).Take(6).ToArray());
                if (isSerial)
                {
                    vcp.Write(request, 0, 11);
                }
                else
                {
                    winUsbDevice.Write(request, 11);
                }

                int r = 0;
                if (isSerial)
                {
                    while ((r += vcp.Read(answer, r, nb + 5 - r)) < nb + 5)
                    {
                    }
                }
                else
                {
                    while ((r += winUsbDevice.Read(answer, r, nb + 5 - r)) < nb + 5)
                    {
                    }
                }

                Array.Copy(answer, 3, response, read, nb);
                offset += nb;
                read   += nb;
            }while (--loop > 0);

            return(response);
        }
Ejemplo n.º 28
0
        private void GetColor(out byte red, out byte green, out byte blue)
        {
            _writeFrameBuffer[0] = 0x80;
            _writeFrameBuffer[1] = 0x01;  // Module command 'Get RGB LED color values'
            for (int i = 2; i < _writeFrameBuffer.Length - 1; i++)
            {
                _writeFrameBuffer[i] = 0x00;
            }
            _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
            _spi.Write(_writeFrameBuffer);

            // now, wait for irq to be asserted
            bool responseReceived = false;
            int  numRetries       = 4;
            int  iRetry           = 0;

            while (true)
            {
                responseReceived = _irqPortInterruptEvent.WaitOne(3, false);

                if (responseReceived || (iRetry >= numRetries - 1))
                {
                    // parse and return the response
                    _writeFrameBuffer[0] = 0x00; // get data from module
                    _writeFrameBuffer[1] = 0x00;
                    _writeFrameBuffer[2] = 0x00;
                    _writeFrameBuffer[3] = 0x00;
                    _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                    _spi.WriteRead(_writeFrameBuffer, _readFrameBuffer);

                    if (_readFrameBuffer[2] == 3)
                    {
                        // Received three byte RGB value
                        red   = _readFrameBuffer[3];
                        green = _readFrameBuffer[4];
                        blue  = _readFrameBuffer[5];
                        return;
                    }
                    else if (iRetry >= numRetries - 1)
                    {
                        red   = 0;
                        blue  = 0;
                        green = 0;
                        return;
                    }
                    else
                    {
                        // failed to receive response; retry
                        responseReceived = false;
                    }
                }
                else
                {
                    // TODO: limit our retries to a handful of retries (or maybe a few dozen -- quickly)
                    // retry infinitely
                    _writeFrameBuffer[0] = 0x80;
                    _writeFrameBuffer[1] = 0x01;  // Module command 'Get RGB LED color values'
                    _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                    _spi.Write(_writeFrameBuffer);
                }

                iRetry++;
            }
        }
Ejemplo n.º 29
0
        internal Guid GetModuleUniqueId(GoSocket socket)
        {
            int frameLength = 1 + 16 + 1;

            byte[] writeFrameBuffer = new byte[frameLength];
            byte[] readFrameBuffer  = new byte[frameLength];

            // get socket's physical pins and SPI bus
            Cpu.Pin        socketGpioPin;
            SPI.SPI_module socketSpiModule;
            Cpu.Pin        socketSpiSlaveSelectPin;
            //
            socket.GetPhysicalResources(out socketGpioPin, out socketSpiModule, out socketSpiSlaveSelectPin);

            SPI.Configuration spiConfig;
            SPI spi;

            try
            {
                spiConfig = new SPI.Configuration(socketSpiSlaveSelectPin, false, 0, 0, false, false, 500, socketSpiModule);
                spi       = new SPI(spiConfig);
            }
            catch
            {
                return(Guid.Empty);
            }

            // TODO: move the socket4ChipSelectDeassert logic to native code (this suppresses the MCO)
            OutputPort socket4ChipSelectDeassert = null;

            if (Port.ReservePin((Cpu.Pin) 0x08, true))
            {
                socket4ChipSelectDeassert = new OutputPort((Cpu.Pin) 0x08, true);
            }

            int iEnumAttempt    = 0;
            int emptyFrameCount = 0;

            byte basicDeviceType = 0x00;

            try
            {
                while (iEnumAttempt < 72)       // NOTE: 72 attempts allow our frame to rotate four full times in case of frame mis-alignment; this should be unnecessary in time.
                {
                    writeFrameBuffer[0] = 0xFE; // 'Enumerate' command
                    for (int i = 1; i < writeFrameBuffer.Length - 1; i++)
                    {
                        writeFrameBuffer[i] = 0xFF; // filler -- so that module sends ID
                    }
                    writeFrameBuffer[writeFrameBuffer.Length - 1] = CRC8.Compute8(writeFrameBuffer, 0, writeFrameBuffer.Length - 1);
                    spi.WriteRead(writeFrameBuffer, readFrameBuffer);

                    // validate the response...
                    bool replyIsBlank = true;
                    for (int i = 1; i < readFrameBuffer.Length - 1; i++)
                    {
                        if (readFrameBuffer[i] != 0)
                        {
                            replyIsBlank = false;
                        }
                    }

                    if (replyIsBlank)
                    {
                        // no response; try again (up to 4 times total)
                        emptyFrameCount++;
                        if (emptyFrameCount > 4)
                        {
                            return(Guid.Empty);
                        }
                    }
                    else if (CRC8.Compute8(readFrameBuffer) == 0)
                    {
                        return(new Guid(Microsoft.SPOT.Hardware.Utility.ExtractRangeFromArray(readFrameBuffer, 1, readFrameBuffer.Length - 2)));
                    }
                    else if (readFrameBuffer[1] != 0)
                    {
                        bool replyIsBasicDevice = true;
                        // did not pass CRC; see if it's a basic device type (first byte is id, then all other bytes including CRC will be zeros)
                        for (int i = 2; i < readFrameBuffer.Length; i++)
                        {
                            if (readFrameBuffer[i] != 0)
                            {
                                replyIsBasicDevice = false;
                            }
                        }

                        if (replyIsBasicDevice)
                        {
                            if (basicDeviceType == 0)
                            {
                                // first successful query; store this id and we'll verify by second enum
                                basicDeviceType = readFrameBuffer[1];
                            }
                            else
                            {
                                if (basicDeviceType == readFrameBuffer[1])
                                {
                                    return(new Guid(Microsoft.SPOT.Hardware.Utility.ExtractRangeFromArray(readFrameBuffer, 1, readFrameBuffer.Length - 2)));
                                }
                                else
                                {
                                    // mismatch; could not enumerate successfully
                                    return(Guid.Empty);
                                }
                            }
                        }
                    }
                    else
                    {
                        // corrupt message; try again
                    }

                    iEnumAttempt++;
                }
            }
            finally
            {
                if (socket4ChipSelectDeassert != null)
                {
                    socket4ChipSelectDeassert.Dispose();
                    Port.ReservePin((Cpu.Pin) 0x08, false);
                }
            }

            // if we reach here, we could not retrieve a GUID.
            return(Guid.Empty);
        }
Ejemplo n.º 30
0
        private void ProcWriteParam(object obj)
        {
            int index = (int)obj;

            int[]  fieldVal = new int[13];
            byte[] bitArray = new byte[12 * 8];

            byte[] byteArray = new byte[12];

            byte[]    dataSend  = new byte[3 + 12];
            FrameUnit frameUnit = FrameManager.CreateFrameUnit(0x14);

            byte[] frameData = new byte[100];
            try
            {
                for (int i = 0; i < 3; i++)
                {
                    switch (tablePSD[index].Rows[i]["TrainState"].ToString())
                    {
                    case "L":
                        fieldVal[0] = 0x1c;
                        break;

                    case "G":
                        fieldVal[0] = 0x26;
                        break;

                    case "R":
                        fieldVal[0] = 0x52;
                        break;

                    default:
                        fieldVal[0] = 0x1c;
                        break;
                    }
                    fieldVal[1] = int.Parse(tablePSD[index].Rows[i]["FZK"].ToString());
                    fieldVal[2] = (int)tablePSD[index].Rows[i]["Crew"];
                    int trip = (int)tablePSD[index].Rows[i]["Trip"];

                    fieldVal[3] = trip % 1000;
                    fieldVal[4] = (int)tablePSD[index].Rows[i]["Dst"];
                    fieldVal[5] = trip / 1000;
                    fieldVal[6] = int.Parse(tablePSD[index].Rows[i]["Res"].ToString());
                    switch (tablePSD[index].Rows[i]["Dir"].ToString())
                    {
                    case "A":
                        fieldVal[7] = 1;
                        break;

                    case "B":
                        fieldVal[7] = 2;
                        break;

                    case "AB":
                        fieldVal[7] = 3;
                        break;

                    case "EAB":
                        fieldVal[7] = 0;
                        break;

                    default:
                        fieldVal[7] = 2;
                        break;
                    }
                    fieldVal[8]  = int.Parse(tablePSD[index].Rows[i]["Err"].ToString());
                    fieldVal[9]  = (int)tablePSD[index].Rows[i]["CarID"];
                    fieldVal[10] = (int)tablePSD[index].Rows[i]["ErrInf"];
                    fieldVal[11] = (int)tablePSD[index].Rows[i]["Mil"];
                    fieldVal[12] = int.Parse(tablePSD[index].Rows[i]["TelID"].ToString());

                    Tool.Field2BitArray(bitArray, fieldVal);

                    Tool.BitArray2ByteArray(bitArray, byteArray);

                    byteArray[11] = CRC8.ComputeCRC8(byteArray, 11, CRC8.CRCExpress);


                    dataSend[0] = 0x14;
                    dataSend[1] = (byte)(((index + 1) << 4) + (i + 1));
                    dataSend[2] = 0x60;
                    Array.Copy(byteArray, 0, dataSend, 3, 12);

                    SerialManager.Send(dataSend, 0, dataSend.Length);

                    if (frameUnit.WaitData(1000))
                    {
                    }
                }

                ShowWriteParamDone("");
            }
            catch (ThreadAbortException)
            {
            }
            finally
            {
            }
        }
Ejemplo n.º 31
0
		//--------
		//-------- Bank specific methods
		//--------
		
		/// <summary> Read a complete memory page with CRC verification provided by the
		/// device with extra information.  Not supported by all devices.
		/// If not extra information available then just call with extraLength=0.
		/// 
		/// </summary>
		/// <param name="page">         page number to read
		/// </param>
		/// <param name="readContinue"> if 'true' then device read is continued without
		/// re-selecting.  This can only be used if the new
		/// readPagePacket() continious where the last one
		/// stopped and it is inside a
		/// 'beginExclusive/endExclusive' block.
		/// </param>
		/// <param name="readBuf">      byte array to put data read. Must have at least
		/// 'getMaxPacketDataLength()' elements.
		/// </param>
		/// <param name="offset">       offset into readBuf to place data
		/// </param>
		/// <param name="extraInfo">    byte array to put extra info read into
		/// </param>
		/// <param name="extraLength">  length of extra information
		/// 
		/// </param>
		/// <throws>  OneWireIOException </throws>
		/// <throws>  OneWireException </throws>
		protected internal virtual void  readPageCRC(int page, bool readContinue, byte[] readBuf, int offset, byte[] extraInfo, int extraLength)
		{
			int len = 0, lastcrc = 0;
			byte[] raw_buf = new byte[pageLength + numCRCBytes];
			
			// only needs to be implemented if supported by hardware
			if (!pageAutoCRC)
				throw new OneWireException("Read page with CRC not supported in this memory bank");
			
			// attempt to put device at max desired speed
			if (!readContinue)
				checkSpeed();
			
			// check if read exceeds memory
			if (page > numberPages)
				throw new OneWireException("Read exceeds memory bank end");
			
			// see if need to access the device
			if (!readContinue)
			{
				
				// select the device
				if (!ib.adapter.select(ib.address))
				{
					forceVerify();
					
					throw new OneWireIOException("Device select failed");
				}
				
				// build start reading memory block with: command, address, (extraInfo?), (crc?)
				len = 3 + extraInfoLength;
				
				if (crcAfterAddress)
					len += numCRCBytes;
				
				Array.Copy(ffBlock, 0, raw_buf, 0, len);
				
				raw_buf[0] = READ_PAGE_WITH_CRC;
				
				int addr = page * pageLength + startPhysicalAddress;
				
				raw_buf[1] = (byte) (addr & 0xFF);
				raw_buf[2] = (byte) ((SupportClass.URShift((addr & 0xFFFF), 8)) & 0xFF);
				
				// do the first block 
				ib.adapter.dataBlock(raw_buf, 0, len);
			}
			else if (extraInfoLength > 0)
			{
				
				// build first block with: extraInfo, crc
				len = extraInfoLength + numCRCBytes;
				
				Array.Copy(ffBlock, 0, raw_buf, 0, len);
				
				// do the first block 
				ib.adapter.dataBlock(raw_buf, 0, len);
			}
			
			// check CRC
			if (numCRCBytes == 2)
				lastcrc = CRC16.compute(raw_buf, 0, len, 0);
			else
				lastcrc = CRC8.compute(raw_buf, 0, len, 0);
			
			if ((extraInfoLength > 0) || (crcAfterAddress))
			{
				
				// check CRC
				if (numCRCBytes == 2)
				{
					if (lastcrc != 0x0000B001)
					{
						forceVerify();
						
						throw new OneWireIOException("Invalid CRC16 read from device");
					}
				}
				else
				{
					if (lastcrc != 0)
					{
						forceVerify();
						
						throw new OneWireIOException("Invalid CRC8 read from device");
					}
				}
				
				lastcrc = 0;
				
				// extract the extra information
				if ((extraInfoLength > 0) && (extraInfo != null))
					Array.Copy(raw_buf, len - extraInfoLength - numCRCBytes, extraInfo, 0, extraLength);
			}
			
			// pre-fill with 0xFF 
			Array.Copy(ffBlock, 0, raw_buf, 0, raw_buf.Length);
			
			// send block to read data + crc
			ib.adapter.dataBlock(raw_buf, 0, raw_buf.Length);
			
			// check the CRC
			if (numCRCBytes == 2)
			{
				if (CRC16.compute(raw_buf, 0, raw_buf.Length, lastcrc) != 0x0000B001)
				{
					forceVerify();
					
					throw new OneWireIOException("Invalid CRC16 read from device");
				}
			}
			else
			{
				if (CRC8.compute(raw_buf, 0, raw_buf.Length, lastcrc) != 0)
				{
					forceVerify();
					
					throw new OneWireIOException("Invalid CRC8 read from device");
				}
			}
			
			// extract the page data
			Array.Copy(raw_buf, 0, readBuf, offset, pageLength);
		}
Ejemplo n.º 32
0
        private void GetFrequency(out double frequency)
        {
            _writeFrameBuffer[0] = 0x80;
            _writeFrameBuffer[1] = 0x01;  // Module command 'Get frequency'
            for (int i = 2; i < _writeFrameBuffer.Length - 1; i++)
            {
                _writeFrameBuffer[i] = 0x00;
            }
            _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
            _spi.Write(_writeFrameBuffer);

            // now, wait for irq to be asserted
            bool responseReceived = false;
            int  numRetries       = 4;
            int  iRetry           = 0;

            while (true)
            {
                responseReceived = _irqPortInterruptEvent.WaitOne(10, false);

                if (responseReceived || (iRetry >= numRetries - 1))
                {
                    // parse and return the response
                    _writeFrameBuffer[0] = 0x00; // get data from module
                    _writeFrameBuffer[1] = 0x00;
                    _writeFrameBuffer[2] = 0x00;
                    _writeFrameBuffer[3] = 0x00;
                    _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                    _spi.WriteRead(_writeFrameBuffer, _readFrameBuffer);

                    if (_readFrameBuffer[2] == 2)
                    {
                        // Received three byte RGB value
                        byte frequencyHighByte = _readFrameBuffer[3];
                        byte frequencyLowByte  = _readFrameBuffer[4];
                        int  divider           = (int)((frequencyHighByte << 8) | frequencyLowByte);
                        frequency = (divider > 0) ? 1000000F / divider : 0F;
                        return;
                    }
                    else if (iRetry >= numRetries - 1)
                    {
                        frequency = 0F;
                        return;
                    }
                    else
                    {
                        // failed to receive response; retry
                        responseReceived = false;
                    }
                }
                else
                {
                    // TODO: limit our retries to a handful of retries (or maybe a few dozen -- quickly)
                    // retry infinitely
                    _writeFrameBuffer[0] = 0x80;
                    _writeFrameBuffer[1] = 0x01;  // Module command 'Get frequency'
                    _writeFrameBuffer[_writeFrameBuffer.Length - 1] = CRC8.Compute8(_writeFrameBuffer, 0, _writeFrameBuffer.Length - 1);
                    _spi.Write(_writeFrameBuffer);
                }

                iRetry++;
            }
        }