/// <summary> /// Read bits from buffer into the lower bits of an unsigned int. /// The LSB contains the latest read bit of the stream. /// (between 1 and 16, inclusive). /// </summary> public int GetBitsFromBuffer(int countBits) { int returnvalue = 0; int sum = m_BitIndex + countBits; // E.B // There is a problem here, wordpointer could be -1 ?! if (m_WordPointer < 0) { m_WordPointer = 0; } // E.B : End. if (sum <= 32) { // all bits contained in *wordpointer returnvalue = SupportClass.URShift(m_FrameBuffer[m_WordPointer], 32 - sum) & bitmask[countBits]; // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits]; if ((m_BitIndex += countBits) == 32) { m_BitIndex = 0; m_WordPointer++; // added by me! } return(returnvalue); } // Magouille a Voir //((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0]; //wordpointer++; // Added by me! //((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0]; int Right = m_FrameBuffer[m_WordPointer] & 0x0000FFFF; m_WordPointer++; int Left = m_FrameBuffer[m_WordPointer] & (int)SupportClass.Identity(0xFFFF0000); returnvalue = ((Right << 16) & (int)SupportClass.Identity(0xFFFF0000)) | (SupportClass.URShift(Left, 16) & 0x0000FFFF); returnvalue = SupportClass.URShift(returnvalue, 48 - sum); // returnvalue >>= 16 - (number_of_bits - (32 - bitindex)) returnvalue &= bitmask[countBits]; m_BitIndex = sum - 32; return(returnvalue); }
/// <summary> Performs the initialisation of the arrays that are used to store the /// values used to write SOP and EPH markers /// /// </summary> private void initSOP_EPHArrays() { // Allocate and set first values of SOP marker as they will not be // modified sopMarker = new byte[CSJ2K.j2k.codestream.Markers.SOP_LENGTH]; sopMarker[0] = unchecked((byte) (CSJ2K.j2k.codestream.Markers.SOP >> 8)); sopMarker[1] = (byte) SupportClass.Identity(CSJ2K.j2k.codestream.Markers.SOP); sopMarker[2] = (byte) 0x00; sopMarker[3] = (byte) 0x04; // Allocate and set values of EPH marker as they will not be // modified ephMarker = new byte[CSJ2K.j2k.codestream.Markers.EPH_LENGTH]; ephMarker[0] = unchecked((byte) (CSJ2K.j2k.codestream.Markers.EPH >> 8)); ephMarker[1] = (byte) SupportClass.Identity(CSJ2K.j2k.codestream.Markers.EPH); }
//-------- //-------- Methods //-------- //-------- //-------- Sensor I/O methods //-------- /// <summary> Retrieves the 1-Wire device sensor state. This state is /// returned as a byte array. Pass this byte array to the 'get' /// and 'set' methods. If the device state needs to be changed then call /// the 'writeDevice' to finalize the changes. /// /// </summary> /// <returns> 1-Wire device sensor state /// /// </returns> /// <throws> OneWireIOException on a 1-Wire communication error such as </throws> /// <summary> reading an incorrect CRC from a 1-Wire device. 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> public virtual byte[] readDevice() { byte[] ret_buf = new byte[4]; if (doSpeedEnable) { doSpeed(); } // read the status byte byte[] tmp_buf = deviceOperation(READ_WRITE_STATUS_COMMAND, (byte)SupportClass.Identity(0x00FF), 2); // extract the status byte ret_buf[0] = tmp_buf[2]; return(ret_buf); }
/// <summary> Reads the subkey requested with the given key name and password. /// Note that this method allows for reading from the subkey data /// only which starts at address 0x10 within a key. It does not allow /// reading from any earlier address within a key because the device /// cannot be force to allow reading the password. This is why the /// subkey number is or-ed with 0x10 in creating the address in bytes /// 1 and 2 of the sendBlock. /// /// </summary> /// <param name="data"> buffer of length 64 into which to write the data /// </param> /// <param name="key"> number indicating the key to be read: 0, 1, or 2 /// </param> /// <param name="passwd"> password of destination subkey /// /// /// </param> /// <throws> IllegalArgumentException If key is out of range (0 to 2), or password is not 8 characters, or if </throws> /// <summary> data does not have a length of 64 /// </summary> /// <throws> OneWireIOException If device is not found on the 1-Wire network </throws> /// <throws> OneWireException on a communication or setup error with the 1-Wire </throws> /// <summary> adapter /// </summary> public virtual void readSubkey(byte[] data, int key, byte[] passwd) { //confirm key and passwd within legal parameters if (key > 0x03) { throw new System.ArgumentException("Key out of range: 0 to 2."); } if (passwd.Length != 8) { throw new System.ArgumentException("Password must contain exactly 8 characters."); } if (data.Length != 64) { throw new System.ArgumentException("Data must be size 64."); } buffer[0] = READ_SUBKEY_COMMAND; buffer[1] = (byte)((key << 6) | 0x10); buffer[2] = (byte)(~buffer[1]); //prepare buffer to receive for (int i = 3; i < 67; i++) { buffer[i] = (byte)SupportClass.Identity(0xFF); } //insert password data Array.Copy(passwd, 0, buffer, 11, 8); //send command block if (adapter.select(address)) { adapter.dataBlock(buffer, 0, 67); adapter.reset(); //create block to send back Array.Copy(buffer, 3, data, 0, 64); } else { //device must not have been present throw new OneWireIOException("MultiKey iButton " + this.AddressAsString + " not found on 1-Wire Network"); } }
/// <summary> /// Fill the header. /// </summary> public static int FourCC(string chunkName) { sbyte[] p = { 0x20, 0x20, 0x20, 0x20 }; SupportClass.GetSBytesFromString ( chunkName, 0, 4, ref p, 0 ); int ret = ((p[0] << 24) & (int)SupportClass.Identity(0xFF000000)) | ((p[1] << 16) & 0x00FF0000) | ((p[2] << 8) & 0x0000FF00) | (p[3] & 0x000000FF); return(ret); }
//-------- //-------- Custom Methods for this iButton Type //-------- //------------------------------------------------------------------------- /// <summary> Reads the Scratchpad of the DS18B20. /// /// </summary> /// <returns> 9-byte buffer representing the scratchpad /// /// </returns> /// <throws> OneWireIOException on a 1-Wire communication error such as </throws> /// <summary> 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'. /// </summary> /// <throws> OneWireException on a communication or setup error with the 1-Wire </throws> /// <summary> adapter /// </summary> 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] = (byte)SupportClass.Identity(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"); }
/// <summary> Write to the Scratch Pad, which is a max of 8 bytes... Note that if /// less than 8 bytes are written, the ending offset will still report /// that a full eight bytes are on the buffer. This means that all 8 bytes /// of the data in the scratchpad will be copied, not just the bytes user /// wrote into it. /// /// </summary> /// <param name="addr"> the address to write the data to /// </param> /// <param name="out_buf"> byte array to write into scratch pad /// </param> /// <param name="offset"> offset into out_buf to write the data /// </param> /// <param name="len"> length of the write data /// /// </param> /// <throws> OneWireIOException </throws> /// <throws> OneWireException </throws> public virtual bool writeScratchpad(int addr, byte[] out_buf, int offset, int len) { byte[] send_block = new byte[14]; // protect send buffer // since the scratchpad is only eight bytes, there is no reason to write // more than eight bytes.. and we can optimize our send buffer's size. if (len > 8) { len = 8; } // access the device if (ib.adapter.select(ib.Address)) { int cnt = 0; // set data block up // start by sending the write scratchpad command send_block[cnt++] = WRITE_SCRATCHPAD_COMMAND; // followed by the target address send_block[cnt++] = (byte)(addr & 0x00FF); send_block[cnt++] = (byte)((SupportClass.URShift((addr & 0x00FFFF), 8)) & 0x00FF); // followed by the data to write to the scratchpad Array.Copy(out_buf, offset, send_block, 3, len); cnt += len; // followed by two bytes for reading CRC16 value send_block[cnt++] = (byte)SupportClass.Identity(0x00FF); send_block[cnt++] = (byte)SupportClass.Identity(0x00FF); // send the data ib.adapter.dataBlock(send_block, 0, cnt); // verify the CRC is correct // if (CRC16.compute(send_block, 0, cnt) != 0x0000B001) // throw new OneWireIOException("Invalid CRC16 in Writing Scratch Pad"); } else { throw new OneWireIOException("Device select failed."); } return(true); }
//-------- //-------- 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> /// <throws> OneWireIOException Error reading data </throws> /// <throws> OneWireException Could not find part </throws> /// <throws> IllegalArgumentException Bad parameters passed </throws> 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] = (byte)SupportClass.Identity(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); }
/* This function handles the increment and decrement operations, * including the contingent reset. You do not need to call reset * between consecutive unit change commands. Both operations issue * the command byte and then recieve the new wiper position. */ //UPGRADE_NOTE: Synchronized keyword was removed from method 'unitChange'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" private int unitChange(byte COMMAND, bool reselect) { lock (this) { if (reselect) { doSpeed(); //don't need to do this if we don't need to select adapter.select(address); } buffer[0] = COMMAND; buffer[1] = (byte)SupportClass.Identity(0x0ff); adapter.dataBlock(buffer, 0, 2); return(0x0ff & buffer[1]); } }
/// <summary> Copy the scratchpad page to memory. /// /// </summary> /// <param name="startAddr"> starting address /// </param> /// <param name="len"> length in bytes that was written already /// /// </param> /// <throws> OneWireIOException </throws> /// <throws> OneWireException </throws> public virtual void copyScratchpad(int startAddr, int len, bool WriteProtect) { int i, j; if (WriteProtect) { i = 2; } else { i = 0; } for (j = 0; j < i; j++) { // select the device if (!ib.adapter.select(ib.address)) { forceVerify(); throw new OneWireIOException("Device select failed"); } // build block to send byte[] raw_buf = new byte[5]; raw_buf[0] = COPY_SCRATCHPAD_COMMAND; raw_buf[1] = (byte)(startAddr & 0xFF); raw_buf[2] = (byte)((SupportClass.URShift((startAddr & 0xFFFF), 8)) & 0xFF); raw_buf[3] = (byte)((startAddr + len - 1) & 0x1F); raw_buf[3] = (byte)((byte)raw_buf[3] | 0x80); // !!! added (byte) raw_buf[4] = (byte)SupportClass.Identity(0xFF); // send block (check copy indication complete) ib.adapter.dataBlock(raw_buf, 0, 5); if ((raw_buf[4] & 0x0F0) != 0) { forceVerify(); throw new OneWireIOException("Copy scratchpad complete not found"); } } }
/// <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); }
/// <summary> Retrieves the 1-Wire device sensor state. This state is /// returned as a byte array. Pass this byte array to the 'get' /// and 'set' methods. If the device state needs to be changed then call /// the 'writeDevice' to finalize the changes. /// /// </summary> /// <returns> 1-Wire device sensor state /// /// </returns> /// <throws> OneWireIOException on a 1-Wire communication error such as </throws> /// <summary> reading an incorrect CRC from a 1-Wire device. 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> public virtual byte[] readDevice() { byte[] buff = new byte[2]; buff[0] = (byte)SupportClass.Identity(0xF5); // PIO Access Read Command buff[1] = (byte)SupportClass.Identity(0xFF); // Used to read the PIO Status Bit Assignment // select the device if (adapter.select(address)) { adapter.dataBlock(buff, 0, 2); } else { throw new OneWireIOException("Device select failed"); } return(buff); }
////////////////////////////////////////////////////////////////////// // Private Methods // ////////////////////////////////////////////////////////////////////// /* This function handles reading of the registers for: * 1. Finding the state of the charge pump * 2. Finding the current location of the wiper * * Both of these operations send one command byte and receive two information bytes. * The relevant information for both is stored in that second received byte. */ //UPGRADE_NOTE: Synchronized keyword was removed from method 'readRegisters'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" private int readRegisters(byte COMMAND) { lock (this) { doSpeed(); if (!adapter.select(address)) { throw new OneWireIOException("Could not select the part!"); } buffer[0] = COMMAND; buffer[1] = buffer[2] = (byte)SupportClass.Identity(0x0ff); adapter.dataBlock(buffer, 0, 3); return(0x0ff & buffer[2]); } }
/// <summary>Copy an array of Strings to bytes.</summary> public static byte[] StringsToByteArray(String[] o, int maxLen) { byte[] res = new byte[o.Length * maxLen]; for (int i = 0; i < o.Length; i += 1) { byte[] bstr = SupportClass.ToByteArray(o[i]); int cnt = bstr.Length; if (cnt > maxLen) { cnt = maxLen; } Array.Copy(bstr, 0, res, i * maxLen, cnt); for (int j = cnt; j < maxLen; j += 1) { res[i * maxLen + j] = (byte)SupportClass.Identity(' '); } } return(res); }
/// <summary> Retrieves the 1-Wire device sensor state. This state is /// returned as a byte array. Pass this byte array to the static query /// and set methods. If the device state needs to be changed then call /// the <CODE>writeDevice</CODE> to finalize the one or more change. /// /// </summary> /// <returns> 1-Wire device sensor state /// /// </returns> /// <throws> OneWireIOException Data was not read correctly </throws> /// <throws> OneWireException Could not find device </throws> public virtual byte[] readDevice() { //format for the byte array is this: //byte 0: Feature register // (msb) bit 7 : Potentiometer resistance msb // bit 6 : Potentiometer resistance lsb // bit 5 : Number of Wiper Positions msb // bit 4 : Number of Wiper Positions lsb // bit 3 : Number of Potentiometers msb // bit 2 : Number of Potentiometers lsb // bit 1 : Wiper Setting Volatility // (lsb) bit 0 : Potentiometer Characteristic (lin/log) //byte 1: Control register // (msb) bit 7 : Reserved // bit 6 : Charge Pump Control // bit 5 : Reserved // bit 4 : Reserved // bit 3 : Inverted Wiper Number msb // bit 2 : Inverted Wiper Number lsb // bit 1 : Wiper Number msb // (lsb) bit 0 : Wiper Number lsb byte[] state = new byte[2]; doSpeed(); if (!adapter.select(address)) { throw new OneWireIOException("Could not select the part!"); } byte[] buf = new byte[3]; buf[0] = READ_CONTROL; buf[1] = buf[2] = (byte)SupportClass.Identity(0x0ff); adapter.dataBlock(buf, 0, 3); state[0] = buf[1]; //feature state[1] = buf[2]; //control return(state); }
/// <summary> Read bits from buffer into the lower bits of an unsigned int. /// The LSB contains the latest read bit of the stream. /// (1 <= number_of_bits <= 16) /// </summary> public int get_bits(int number_of_bits) { int returnvalue = 0; int sum = bitindex + number_of_bits; // E.B // There is a problem here, wordpointer could be -1 ?! if (wordpointer < 0) { wordpointer = 0; } // E.B : End. if (sum <= 32) { // all bits contained in *wordpointer returnvalue = (SupportClass.URShift(framebuffer[wordpointer], (32 - sum))) & bitmask[number_of_bits]; // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits]; if ((bitindex += number_of_bits) == 32) { bitindex = 0; wordpointer++; // added by me! } return(returnvalue); } // Magouille a Voir //((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0]; //wordpointer++; // Added by me! //((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0]; int Right = (framebuffer[wordpointer] & 0x0000FFFF); wordpointer++; int Left = (framebuffer[wordpointer] & (int)SupportClass.Identity(0xFFFF0000)); returnvalue = ((Right << 16) & (int)SupportClass.Identity(0xFFFF0000)) | ((SupportClass.URShift(Left, 16)) & 0x0000FFFF); returnvalue = SupportClass.URShift(returnvalue, 48 - sum); // returnvalue >>= 16 - (number_of_bits - (32 - bitindex)) returnvalue &= bitmask[number_of_bits]; bitindex = sum - 32; return(returnvalue); }
//-------- //-------- Constructor //-------- /// <summary> Memory bank contstuctor. Requires reference to the OneWireContainer /// this memory bank resides on. Requires reference to memory banks used /// in OTP operations. /// </summary> public MemoryBankEEPROM(OneWireContainer ibutton, ScratchPad scratch) { // keep reference to ibutton where memory bank is ib = ibutton; // keep reference to scratchPad bank sp = scratch; // get references to MemoryBanks used in OTP operations, assume locking mbLock = null; lockPage_Renamed_Field = true; // initialize attributes of this memory bank - DEFAULT: Main memory DS2431 generalPurposeMemory = true; bankDescription = "Main memory"; numberPages = 4; size = 128; pageLength = 32; maxPacketDataLength = 29; readWrite = true; writeOnce = false; readOnly = false; nonVolatile = true; pageAutoCRC = false; lockPage_Renamed_Field = true; programPulse = false; powerDelivery = true; extraInfo = false; extraInfoLength = 0; extraInfoDescription = null; writeVerification = false; startPhysicalAddress = 0; doSetSpeed = true; scratchPadSize = 8; // create the ffblock (used for faster 0xFF fills) for (int i = 0; i < 500; i++) { ffBlock[i] = (byte)SupportClass.Identity(0xFF); } }
internal static int[] float_values(WavpackStream wps, int[] values, long num_values, int bufferStartPos) { int shift = wps.float_max_exp - wps.float_norm_exp + wps.float_shift; int value_counter = bufferStartPos; if (shift > 32) { shift = 32; } else if (shift < -32) { shift = -32; } while (num_values > 0) { if (shift > 0) { values[value_counter] <<= shift; } else if (shift < 0) { values[value_counter] >>= -shift; } if (values[value_counter] > 8388607L) { values[value_counter] = (int)SupportClass.Identity(8388607L); } else if (values[value_counter] < -8388608L) { values[value_counter] = (int)SupportClass.Identity(-8388608L); } value_counter++; num_values--; } return(values); }
//-------- //-------- Constructor //-------- /// <summary> Memory bank contstuctor. Requires reference to the OneWireContainer /// this memory bank resides on. /// </summary> public MemoryBankEE(OneWireContainer ibutton) { lock (this) { // keep reference to ibutton where memory bank is ib = ibutton; // create the ffblock (used for faster 0xFF fills) ffBlock = new byte[50]; for (int i = 0; i < 50; i++) { ffBlock[i] = (byte)SupportClass.Identity(0xFF); } // defaults writeVerification = true; // indicate speed has not been set doSetSpeed = true; } }
//-------- //-------- Constructor //-------- /// <summary> Memory bank contstuctor. Requires reference to the OneWireContainer /// this memory bank resides on. /// </summary> public MemoryBankScratch(OneWireContainer ibutton) { // keep reference to ibutton where memory bank is ib = ibutton; // initialize attributes of this memory bank - DEFAULT: DS199X scratchapd bankDescription = "Scratchpad"; generalPurposeMemory = false; startPhysicalAddress = 0; size = 32; readWrite = true; writeOnce = false; readOnly = false; nonVolatile = false; programPulse = false; powerDelivery = false; writeVerification = true; numberPages = 1; pageLength = 32; maxPacketDataLength = 29; pageAutoCRC = false; extraInfo = true; extraInfoLength = 3; extraInfoDescription = "Target address, offset"; // create the ffblock (used for faster 0xFF fills) ffBlock = new byte[96]; for (int i = 0; i < 96; i++) { ffBlock[i] = (byte)SupportClass.Identity(0xFF); } // default copy scratchpad command COPY_SCRATCHPAD_COMMAND = (byte)0x55; // indicate speed has not been set doSetSpeed = true; }
/// <summary> /// Parses the data previously read with read_frame_data(). /// </summary> internal void ParseFrame() { // Convert Bytes read to int int b = 0; sbyte[] byteread = m_FrameBytes; int bytesize = m_FrameSize; for (int k = 0; k < bytesize; k = k + 4) { sbyte b0 = 0; sbyte b1 = 0; sbyte b2 = 0; sbyte b3 = 0; b0 = byteread[k]; if (k + 1 < bytesize) { b1 = byteread[k + 1]; } if (k + 2 < bytesize) { b2 = byteread[k + 2]; } if (k + 3 < bytesize) { b3 = byteread[k + 3]; } m_FrameBuffer[b++] = ((b0 << 24) & (int)SupportClass.Identity(0xFF000000)) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00) | (b3 & 0x000000FF); } m_WordPointer = 0; m_BitIndex = 0; }
/// <summary> Updates the latch state for the 2 general purpose PIO pins. This /// has the side-effect of also sampling the PIO pins level after updating /// the latch, so the state buffer is updated with this new level information. /// /// </summary> /// <param name="state">1-Wire device sensor state /// /// </param> /// <throws> OneWireIOException on a 1-Wire communication error such as </throws> /// <summary> reading an incorrect CRC from a 1-Wire device. 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> public virtual void writeDevice(byte[] state) { //channel Access Write adapter.assertSelect(address); byte[] buffer = new byte[5]; buffer[0] = PIO_ACCESS_WRITE; buffer[1] = state[1]; buffer[2] = (byte)~state[1]; buffer[3] = (byte)SupportClass.Identity(0xFF); buffer[4] = (byte)SupportClass.Identity(0xFF); adapter.dataBlock(buffer, 0, 5); if (buffer[3] != (byte)SupportClass.Identity(0x00AA)) { throw new OneWireIOException("Failure to change latch state."); } // update sensed logic level in state. state[0] = buffer[4]; }
//-------- //-------- Constructor //-------- /// <summary> Memory bank contstuctor. Requires reference to the OneWireContainer /// this memory bank resides on. DEFAULT: DS1993 main memory /// /// </summary> /// <param name="ibutton">ibutton container that this memory bank resides in /// </param> /// <param name="scratchPad">memory bank referece for scratchpad, used when writing /// </param> public MemoryBankNV(OneWireContainer ibutton, ScratchPad scratch) { // keep reference to ibutton where memory bank is ib = ibutton; // keep reference to scratchPad bank sp = scratch; // initialize attributes of this memory bank - DEFAULT: DS1993 main memory bankDescription = "Main Memory"; generalPurposeMemory = true; startPhysicalAddress = 0; size = 512; readWrite = true; writeOnce = false; readOnly = false; nonVolatile = true; programPulse = false; powerDelivery = false; writeVerification = true; numberPages = 16; pageLength = 32; maxPacketDataLength = 29; pageAutoCRC = false; extraInfo = false; extraInfoLength = 0; extraInfoDescription = null; // create the ffblock (used for faster 0xFF fills) ffBlock = new byte[96]; for (int i = 0; i < 96; i++) { ffBlock[i] = (byte)SupportClass.Identity(0xFF); } }
/// <summary> Open a RIFF file. /// </summary> public virtual int Open(System.String Filename, int NewMode) { int retcode = DDC_SUCCESS; if (fmode != RFM_UNKNOWN) { retcode = Close(); } if (retcode == DDC_SUCCESS) { switch (NewMode) { case RFM_WRITE: try { file = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(Filename, "rw"); try { // Write the RIFF header... // We will have to come back later and patch it! sbyte[] br = new sbyte[8]; br[0] = (sbyte)((SupportClass.URShift(riff_header.ckID, 24)) & 0x000000FF); br[1] = (sbyte)((SupportClass.URShift(riff_header.ckID, 16)) & 0x000000FF); br[2] = (sbyte)((SupportClass.URShift(riff_header.ckID, 8)) & 0x000000FF); br[3] = (sbyte)(riff_header.ckID & 0x000000FF); sbyte br4 = (sbyte)((SupportClass.URShift(riff_header.ckSize, 24)) & 0x000000FF); sbyte br5 = (sbyte)((SupportClass.URShift(riff_header.ckSize, 16)) & 0x000000FF); sbyte br6 = (sbyte)((SupportClass.URShift(riff_header.ckSize, 8)) & 0x000000FF); sbyte br7 = (sbyte)(riff_header.ckSize & 0x000000FF); br[4] = br7; br[5] = br6; br[6] = br5; br[7] = br4; file.Write(SupportClass.ToByteArray(br), 0, 8); fmode = RFM_WRITE; } catch (System.IO.IOException ioe) { file.Close(); fmode = RFM_UNKNOWN; } } catch (System.IO.IOException ioe) { fmode = RFM_UNKNOWN; retcode = DDC_FILE_ERROR; } break; case RFM_READ: try { file = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(Filename, "r"); try { // Try to read the RIFF header... sbyte[] br = new sbyte[8]; SupportClass.ReadInput(file, ref br, 0, 8); fmode = RFM_READ; riff_header.ckID = ((br[0] << 24) & (int)SupportClass.Identity(0xFF000000)) | ((br[1] << 16) & 0x00FF0000) | ((br[2] << 8) & 0x0000FF00) | (br[3] & 0x000000FF); riff_header.ckSize = ((br[4] << 24) & (int)SupportClass.Identity(0xFF000000)) | ((br[5] << 16) & 0x00FF0000) | ((br[6] << 8) & 0x0000FF00) | (br[7] & 0x000000FF); } catch (System.IO.IOException ioe) { file.Close(); fmode = RFM_UNKNOWN; } } catch (System.IO.IOException ioe) { fmode = RFM_UNKNOWN; retcode = DDC_FILE_ERROR; } break; default: retcode = DDC_INVALID_CALL; break; } } return(retcode); }
/// <summary> This method creates the tileparts from the buffered tile headers, /// packet headers and packet data /// /// </summary> /// <exception cref="IOException">If an I/O error ocurred. /// /// </exception> private void createTileParts() { int i, prem, t, length; int pIndex; // phIndex removed int tppStart; int tilePart; int p, np, nomnp; int numTileParts; int numPackets; System.IO.MemoryStream temp = new System.IO.MemoryStream(); byte[] tempByteArr; // Create tile parts tileParts = new byte[nt][][]; maxtp = 0; for (t = 0; t < nt; t++) { // Calculate number of tile parts. If tileparts are not used, // put all packets in the first tilepart if (pptp == 0) { pptp = ppt[t]; } prem = ppt[t]; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" numTileParts = (int)System.Math.Ceiling(((double)prem) / pptp); numPackets = packetHeaders[t].Length; maxtp = (numTileParts > maxtp)?numTileParts:maxtp; tileParts[t] = new byte[numTileParts][]; // Create all the tile parts for tile t tppStart = 0; pIndex = 0; p = 0; //phIndex = 0; for (tilePart = 0; tilePart < numTileParts; tilePart++) { // Calculate number of packets in this tilepart nomnp = (pptp > prem)?prem:pptp; np = nomnp; // Write tile part header if (tilePart == 0) { // Write original tile part header up to SOD marker temp.Write(tileHeaders[t], 0, tileHeaders[t].Length - 2); } else { // Write empty header of length TP_HEAD_LEN-2 temp.Write(new byte[TP_HEAD_LEN - 2], 0, TP_HEAD_LEN - 2); } // Write PPT marker segments if PPT used if (pptUsed) { int pptLength = 3; // Zppt and Lppt int pptIndex = 0; int phLength; p = pIndex; while (np > 0) { phLength = packetHeaders[t][p].Length; // If the total legth of the packet headers is greater // than MAX_LPPT, several PPT markers are needed if (pptLength + phLength > CSJ2K.j2k.codestream.Markers.MAX_LPPT) { temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8)); temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPT & 0x00FF)); temp.WriteByte((System.Byte)SupportClass.URShift(pptLength, 8)); temp.WriteByte((System.Byte)pptLength); temp.WriteByte((System.Byte)pptIndex++); for (i = pIndex; i < p; i++) { temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length); } pptLength = 3; // Zppt and Lppt pIndex = p; } pptLength += phLength; p++; np--; } // Write last PPT marker temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8)); temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPT & 0x00FF)); temp.WriteByte((System.Byte)SupportClass.URShift(pptLength, 8)); temp.WriteByte((System.Byte)pptLength); temp.WriteByte((System.Byte)pptIndex); for (i = pIndex; i < p; i++) { temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length); } } pIndex = p; np = nomnp; // Write SOD marker temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOD, 8)); temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.SOD & 0x00FF)); // Write packet data and packet headers if PPT and PPM not used for (p = tppStart; p < tppStart + np; p++) { if (!tempSop) { temp.Write(sopMarkSeg[t][p], 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH); } if (!(ppmUsed || pptUsed)) { temp.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length); } temp.Write(packetData[t][p], 0, packetData[t][p].Length); } tppStart += np; // Edit tile part header tempByteArr = temp.ToArray(); tileParts[t][tilePart] = tempByteArr; length = (int)temp.Length; if (tilePart == 0) { // Edit first tile part header tempByteArr[6] = (byte)(SupportClass.URShift(length, 24)); // Psot tempByteArr[7] = (byte)(SupportClass.URShift(length, 16)); tempByteArr[8] = (byte)(SupportClass.URShift(length, 8)); tempByteArr[9] = (byte)(length); tempByteArr[10] = (byte)SupportClass.Identity((0)); // TPsot tempByteArr[11] = (byte)(numTileParts); // TNsot } else { // Edit tile part header tempByteArr[0] = (byte)(SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOT, 8)); // SOT tempByteArr[1] = (byte)(CSJ2K.j2k.codestream.Markers.SOT & 0x00FF); tempByteArr[2] = (byte)SupportClass.Identity((0)); // Lsot tempByteArr[3] = (byte)SupportClass.Identity((10)); tempByteArr[4] = (byte)(SupportClass.URShift(t, 8)); // Isot tempByteArr[5] = (byte)(t); // tempByteArr[6] = (byte)(SupportClass.URShift(length, 24)); // Psot tempByteArr[7] = (byte)(SupportClass.URShift(length, 16)); tempByteArr[8] = (byte)(SupportClass.URShift(length, 8)); tempByteArr[9] = (byte)(length); tempByteArr[10] = (byte)(tilePart); //TPsot tempByteArr[11] = (byte)(numTileParts); // TNsot } //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" //temp.reset(); temp.SetLength(0); prem -= np; } } temp.Dispose(); }
// Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). private static ByteMatrix renderResult(QRCode code, int width, int height) { ByteMatrix input = code.Matrix; int inputWidth = input.Width; int inputHeight = input.Height; int qrWidth = inputWidth + (QUIET_ZONE_SIZE << 1); int qrHeight = inputHeight + (QUIET_ZONE_SIZE << 1); int outputWidth = System.Math.Max(width, qrWidth); int outputHeight = System.Math.Max(height, qrHeight); int multiple = System.Math.Min(outputWidth / qrWidth, outputHeight / qrHeight); // Padding includes both the quiet zone and the extra white pixels to accommodate the requested // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will // handle all the padding from 100x100 (the actual QR) up to 200x160. int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; int topPadding = (outputHeight - (inputHeight * multiple)) / 2; ByteMatrix output = new ByteMatrix(outputWidth, outputHeight); sbyte[,] outputArray = output.Array; // We could be tricky and use the first row in each set of multiple as the temporary storage, // instead of allocating this separate array. sbyte[] row = new sbyte[outputWidth]; // 1. Write the white lines at the top for (int y = 0; y < topPadding; y++) { setRowColor(output.GetRow(y), (sbyte)SupportClass.Identity(255)); } // 2. Expand the QR image to the multiple sbyte[,] inputArray = input.Array; for (int y = 0; y < inputHeight; y++) { // a. Write the white pixels at the left of each row for (int x = 0; x < leftPadding; x++) { row[x] = (sbyte)SupportClass.Identity(255); } // b. Write the contents of this row of the barcode int offset = leftPadding; for (int x = 0; x < inputWidth; x++) { // Redivivus.in Java to c# Porting update - Type cased sbyte // 30/01/2010 // sbyte value_Renamed = (inputArray[y][x] == 1)?0:(sbyte) SupportClass.Identity(255); sbyte value_Renamed = (sbyte)((inputArray[y, x] == 1) ? 0 : SupportClass.Identity(255)); for (int z = 0; z < multiple; z++) { row[offset + z] = value_Renamed; } offset += multiple; } // c. Write the white pixels at the right of each row offset = leftPadding + (inputWidth * multiple); for (int x = offset; x < outputWidth; x++) { row[x] = (sbyte)SupportClass.Identity(255); } // d. Write the completed row multiple times offset = topPadding + (y * multiple); for (int z = 0; z < multiple; z++) { Array.Copy(row, 0, output.GetRow(offset + z), 0, outputWidth); } } // 3. Write the white lines at the bottom int offset2 = topPadding + (inputHeight * multiple); for (int y = offset2; y < outputHeight; y++) { setRowColor(output.GetRow(y), (sbyte)SupportClass.Identity(255)); } return(output); }
internal Crc16() { _CRC = (short)SupportClass.Identity(0xFFFF); }
static Crc16() { Polynomial = (short)SupportClass.Identity(0x8005); }
private static System.String guessEncoding(sbyte[] bytes) { if (ASSUME_SHIFT_JIS) { return(SHIFT_JIS); } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.Length > 3 && bytes[0] == (sbyte)SupportClass.Identity(0xEF) && bytes[1] == (sbyte)SupportClass.Identity(0xBB) && bytes[2] == (sbyte)SupportClass.Identity(0xBF)) { return(UTF8); } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.Length; bool canBeISO88591 = true; bool canBeShiftJIS = true; int maybeDoubleByteCount = 0; int maybeSingleByteKatakanaCount = 0; bool sawLatin1Supplement = false; bool lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value_Renamed = bytes[i] & 0xFF; if ((value_Renamed == 0xC2 || value_Renamed == 0xC3) && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value_Renamed == 0xC2 && nextValue >= 0xA0) || (value_Renamed == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value_Renamed >= 0x7F && value_Renamed <= 0x9F) { canBeISO88591 = false; } if (value_Renamed >= 0xA1 && value_Renamed <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value_Renamed >= 0xF0 && value_Renamed <= 0xFF) || value_Renamed == 0x80 || value_Renamed == 0xA0)) { canBeShiftJIS = false; } if (((value_Renamed >= 0x81 && value_Renamed <= 0x9F) || (value_Renamed >= 0xE0 && value_Renamed <= 0xEF))) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; if (i >= bytes.Length - 1) { canBeShiftJIS = false; } else { int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } else { maybeDoubleByteCount++; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) { return(SHIFT_JIS); } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return(ISO88591); } // Otherwise, we take a wild guess with UTF-8 return(UTF8); }
/// <summary> Write memory in the current bank. It is recommended that /// when writing data that some structure in the data is created /// to provide error free reading back with read(). Or the /// method 'writePagePacket()' could be used which automatically /// wraps the data in a length and CRC. /// /// When using on Write-Once devices care must be taken to write into /// into empty space. If write() is used to write over an unlocked /// page on a Write-Once device it will fail. If write verification /// is turned off with the method 'setWriteVerification(false)' then /// the result will be an 'AND' of the existing data and the new data. /// /// </summary> /// <param name="startAddr"> starting address /// </param> /// <param name="writeBuf"> byte array containing data to write /// </param> /// <param name="offset"> offset into writeBuf to get data /// </param> /// <param name="len"> length in bytes to write /// /// </param> /// <throws> OneWireIOException </throws> /// <throws> OneWireException </throws> public virtual void write(int startAddr, byte[] writeBuf, int offset, int len) { int i; byte[] es_data = new byte[3]; byte[] scratchpad = new byte[8]; // return if nothing to do if (len == 0) { return; } // attempt to put device at speed checkSpeed(); // check if write exceeds memory if ((startAddr + len) > size) { throw new OneWireException("Write exceeds memory bank end"); } // check if trying to write read only bank if (ReadOnly && (((startPhysicalAddress + startAddr) != 137) && (len != 1))) { throw new OneWireException("Trying to write read-only memory bank"); } if (((startPhysicalAddress + startAddr) == 137) && (len == 1)) { ib.adapter.select(ib.address); byte[] buffer = new byte[5]; buffer[0] = CHANNEL_ACCESS_WRITE; buffer[1] = writeBuf[offset]; buffer[2] = (byte)~writeBuf[offset]; Array.Copy(ffBlock, 0, buffer, 3, 2); ib.adapter.dataBlock(buffer, 0, 5); if (buffer[3] != (byte)SupportClass.Identity(0x00AA)) { //throw new OneWireIOException("Failure to change DS2408 latch state: buffer=" + Convert.toHexString(buffer)); throw new OneWireIOException("Failure to change DS2408 latch state: buffer=" + com.dalsemi.onewire.utils.Convert.toHexString(buffer)); // !!! } } else if (((startPhysicalAddress + startAddr) > 138) && ((startPhysicalAddress + startAddr + len) < 143)) { ib.adapter.select(ib.address); byte[] buffer = new byte[6]; buffer[0] = (byte)SupportClass.Identity(0xCC); buffer[1] = (byte)((startAddr + startPhysicalAddress) & 0xFF); buffer[2] = (byte)((SupportClass.URShift(((startAddr + startPhysicalAddress) & 0xFFFF), 8)) & 0xFF); Array.Copy(writeBuf, offset, buffer, 3, len); ib.adapter.dataBlock(buffer, 0, len + 3); } else if (((startPhysicalAddress + startAddr) > 127) && ((startPhysicalAddress + startAddr + len) < 130)) { byte[] buffer = new byte[8]; int addr = 128; byte[] buff = new byte[11]; Array.Copy(ffBlock, 0, buff, 0, 11); ib.adapter.select(ib.address); buff[0] = READ_MEMORY_COMMAND; // address 1 buff[1] = (byte)(addr & 0xFF); // address 2 buff[2] = (byte)((SupportClass.URShift((addr & 0xFFFF), 8)) & 0xFF); ib.adapter.dataBlock(buff, 0, 11); // extract the data Array.Copy(buff, 3, buffer, 0, 8); Array.Copy(writeBuf, offset, buffer, 0, len); // write the page of data to scratchpad if (!writeScratchpad(startPhysicalAddress + startAddr, buffer, 0, 8)) { throw new OneWireIOException("Invalid CRC16 in write"); } if (!readScratchpad(scratchpad, 0, 8, es_data)) { throw new OneWireIOException("Read scratchpad was not successful."); } if ((es_data[2] & 0x20) == 0x20) { throw new OneWireIOException("The write scratchpad command was not completed."); } else { for (i = 0; i < 8; i++) { if (scratchpad[i] != buffer[i]) { throw new OneWireIOException("The read back of the data in the scratch pad did " + "not match."); } } } // Copy data from scratchpad into memory copyScratchpad(es_data); } else { throw new OneWireIOException("Trying to write read-only memory."); } }