From 47db415506abbabc4a9703e1e68c2b78e4275bc1 Mon Sep 17 00:00:00 2001 From: Chris Kaczor Date: Fri, 16 Jan 2015 17:55:23 -0500 Subject: [PATCH] Code modernization --- TMEX.cs | 152 ++++++++--------- owAdapter.cs | 255 +++++++++++++--------------- owCRC16.cs | 36 ++-- owCRC8.cs | 104 +++++------- owDevice.cs | 32 +--- owDeviceFamily10.cs | 144 ++++++++-------- owDeviceFamily12.cs | 293 +++++++++++++++----------------- owDeviceFamily1D.cs | 107 ++++++------ owDeviceFamily20.cs | 386 ++++++++++++++++++++--------------------- owDeviceFamily26.cs | 405 +++++++++++++++++++++----------------------- owDeviceFamilyFF.cs | 260 ++++++++++++++-------------- owException.cs | 70 ++++---- owIdentifer.cs | 61 +++---- owNetwork.cs | 65 ++----- owSession.cs | 39 ++--- 15 files changed, 1097 insertions(+), 1312 deletions(-) diff --git a/TMEX.cs b/TMEX.cs index 2eec9de..0a4c4c4 100644 --- a/TMEX.cs +++ b/TMEX.cs @@ -3,132 +3,120 @@ using System.Runtime.InteropServices; namespace OneWireAPI { - public class TMEX - { - #region TMEX function enumerations + public class TMEX + { + // Size of the global state buffer + public enum StateBufferSize + { + NoEpromWriting = 5120, + EpromWriting = 15360 + } - // Size of the global state buffer - public enum TMStateBufferSize - { - NoEPROMWriting = 5120, - EPROMWriting = 15360 - } + // Type of operation for the TMOneWireLevel function + public enum LevelOperation : short + { + Write = 0, + Read = 1 + } - // Type of operation for the TMOneWireLevel function - public enum TMOneWireLevelOperation : short - { - Write = 0, - Read = 1 - } + // TMOneWireLevel operation mode + public enum LevelMode : short + { + Normal = 0x0, + StrongPullup = 0x1, + Break = 0x2, + ProgramVoltage = 0x3 + } - // TMOneWireLevel operation mode - public enum TMOneWireLevelMode : short - { - Normal = 0x0, - StrongPullup = 0x1, - Break = 0x2, - ProgramVoltage = 0x3 - } + // When the mode from the TMOneWireLevel is to activate + public enum LevelPrime : short + { + Immediate = 0, + AfterNextBit = 1, + AfterNextByte = 2 + } - // When the mode from the TMOneWireLevel is to activate - public enum TMOneWireLevelPrime : short - { - Immediate = 0, - AfterNextBit = 1, - AfterNextByte = 2 - } + // Type of CRC to be calculated + public enum CrcType : short + { + EightBit = 0, + SixteenBit = 1 + } - // Type of CRC to be calculated - public enum TMCRCType : short - { - EightBit = 0, - SixteenBit = 1 - } - - #endregion - - #region TMEX function structures - - [StructLayoutAttribute(LayoutKind.Sequential, Pack=1)] - public struct FileEntry - { - [MarshalAs(UnmanagedType.ByValArray,SizeConst=4)] - public byte[] Name; /* four-character file name */ - public byte Extension; /* extension number, range 0 - 99, 127 */ - public byte StartPage; /* page number where file starts */ - public byte PageCount; /* number of pages occupied by file */ - public byte Attributes; /* file/directory attribute */ - [MarshalAs(UnmanagedType.ByValArray,SizeConst=32)] - public byte[] Bitmap; /* current bitmap of the device */ - } - - #endregion - - #region TMEX DLL function imports - - [DllImport("IBFS64.DLL")] - public static extern short Get_Version(byte[] baVersion); + [StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)] + public struct FileEntry + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] + public byte[] Name; /* four-character file name */ + public byte Extension; /* extension number, range 0 - 99, 127 */ + public byte StartPage; /* page number where file starts */ + public byte PageCount; /* number of pages occupied by file */ + public byte Attributes; /* file/directory attribute */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public byte[] Bitmap; /* current bitmap of the device */ + } [DllImport("IBFS64.DLL")] - public static extern int TMExtendedStartSession(short nPortNumber, short nPortType, IntPtr nEnhancedOptions); + public static extern short Get_Version(byte[] version); [DllImport("IBFS64.DLL")] - public static extern short TMEndSession(int iSession); + public static extern int TMExtendedStartSession(short portNumber, short portType, IntPtr enhancedOptions); [DllImport("IBFS64.DLL")] - public static extern short TMReadDefaultPort(out short nPortNumber, out short nPortType); + public static extern short TMEndSession(int session); [DllImport("IBFS64.DLL")] - public static extern short TMSetup(int iSession); + public static extern short TMReadDefaultPort(out short portNumber, out short portType); [DllImport("IBFS64.DLL")] - public static extern short TMClose(int iSession); + public static extern short TMSetup(int session); [DllImport("IBFS64.DLL")] - public static extern short TMRom(int iSession, byte[] bStateBuffer, short[] nROM); + public static extern short TMClose(int session); [DllImport("IBFS64.DLL")] - public static extern short TMAccess(int iSession, byte[] bStateBuffer); + public static extern short TMRom(int session, byte[] stateBuffer, short[] rom); [DllImport("IBFS64.DLL")] - public static extern short TMOneWireLevel(int iSession, TMOneWireLevelOperation nOperation, TMOneWireLevelMode nLevelMode, TMOneWireLevelPrime nPrimed); + public static extern short TMAccess(int session, byte[] stateBuffer); [DllImport("IBFS64.DLL")] - public static extern short TMTouchBit(int iSession, short nOutput); + public static extern short TMOneWireLevel(int session, LevelOperation operation, LevelMode levelMode, LevelPrime primed); [DllImport("IBFS64.DLL")] - public static extern short TMTouchByte(int iSession, short nOutput); + public static extern short TMTouchBit(int session, short output); [DllImport("IBFS64.DLL")] - public static extern short TMTouchReset(int iSession); + public static extern short TMTouchByte(int session, short output); [DllImport("IBFS64.DLL")] - public static extern short TMBlockStream(int iSession, byte[] aData, short nByteCount); + public static extern short TMTouchReset(int session); [DllImport("IBFS64.DLL")] - public static extern short TMBlockIO(int iSession, byte[] aData, short nByteCount); + public static extern short TMBlockStream(int session, byte[] data, short byteCount); [DllImport("IBFS64.DLL")] - public static extern short TMCRC(short nLength, byte[] aData, ushort nSeed, TMCRCType nType); + public static extern short TMBlockIO(int session, byte[] data, short byteCount); [DllImport("IBFS64.DLL")] - public static extern short TMFirst(int iSession, byte[] bStateBuffer); + public static extern short TMCRC(short length, byte[] data, ushort seed, CrcType type); [DllImport("IBFS64.DLL")] - public static extern short TMNext(int iSession, byte[] bStateBuffer); + public static extern short TMFirst(int session, byte[] stateBuffer); [DllImport("IBFS64.DLL")] - public static extern short TMFirstFile(int iSession, byte[] bStateBuffer, ref FileEntry uFileEntry); + public static extern short TMNext(int session, byte[] stateBuffer); [DllImport("IBFS64.DLL")] - public static extern short TMOpenFile(int iSession, byte[] bStateBuffer, ref FileEntry uFileEntry); + public static extern short TMFirstFile(int session, byte[] stateBuffer, ref FileEntry fileEntry); [DllImport("IBFS64.DLL")] - public static extern short TMReadFile(int iSession, byte[] bStateBuffer, short nFileHandle, byte[] baReadBuffer, short nBufferSize); + public static extern short TMOpenFile(int session, byte[] stateBuffer, ref FileEntry fileEntry); [DllImport("IBFS64.DLL")] - public static extern short TMCloseFile(int iSession, byte[] bStateBuffer, short nFileHandle); + public static extern short TMReadFile(int session, byte[] stateBuffer, short fileHandle, byte[] readBuffer, short bufferSize); - #endregion - } + [DllImport("IBFS64.DLL")] + public static extern short TMCloseFile(int session, byte[] stateBuffer, short fileHandle); + } } diff --git a/owAdapter.cs b/owAdapter.cs index 2114b3c..dc8f63d 100644 --- a/owAdapter.cs +++ b/owAdapter.cs @@ -1,165 +1,150 @@ -using System; - namespace OneWireAPI { - public class owAdapter - { - #region Member variables + public class owAdapter + { + private static owSession _session; + private static owIdentifier _lastId; - private static owSession m_oSession; // The current session - private static owIdentifier m_oLastID; // Last ID selected + public static void Initialize(owSession session) + { + // Store the session we are dealing with + _session = session; + } - #endregion + public static void Select(owIdentifier id) + { + // Set the ID of the device we want to talk to + var result = TMEX.TMRom(_session.SessionHandle, _session.StateBuffer, id.RawId); - #region Methods + // Check the result + if (result != 1) + { + // Throw a ROM exception + throw new owException(owException.ExceptionFunction.Select, id, result); + } - public static void Initialize(owSession Session) - { - // Store the session we are dealing with - m_oSession = Session; - } + // Copy the ID as the last selected ID + _lastId = id; - public static void Select(owIdentifier ID) - { - // Set the ID of the device we want to talk to - short nResult = TMEX.TMRom(m_oSession.SessionHandle, m_oSession.StateBuffer, ID.RawID); + // Access the device + Access(); + } - // Check the result - if (nResult != 1) - { - // Throw a ROM exception - throw new owException(owException.owExceptionFunction.Select, ID, nResult); - } + public static void Access() + { + // Attempt to access the device + var result = TMEX.TMAccess(_session.SessionHandle, _session.StateBuffer); - // Copy the ID as the last selected ID - m_oLastID = ID; + // Check to see if we could access the device + if (result != 1) + { + // Throw an access exception + throw new owException(owException.ExceptionFunction.Access, _lastId, result); + } + } - // Access the device - Access(); - } + public static short SendBlock(byte[] data, short byteCount) + { + // Send the block and return the result + var result = TMEX.TMBlockStream(_session.SessionHandle, data, byteCount); - public static void Access() - { - // Attempt to access the device - short nResult = TMEX.TMAccess(m_oSession.SessionHandle, m_oSession.StateBuffer); + // Check to see if the bytes sent matches the value returned + if (result != byteCount) + { + // Throw an access exception + throw new owException(owException.ExceptionFunction.SendBlock, _lastId, result); + } - // Check to see if we could access the device - if (nResult != 1) - { - // Throw an access exception - throw new owException(owException.owExceptionFunction.Access, m_oLastID, nResult); - } - } + // Return the result + return result; + } - public static short SendBlock(byte[] Data, short ByteCount) - { - // Send the block and return the result - short nResult = TMEX.TMBlockStream(m_oSession.SessionHandle, Data, ByteCount); + public static short SendBlock(byte[] data, short byteCount, bool reset) + { + // Send the block and return the result + var result = reset ? TMEX.TMBlockStream(_session.SessionHandle, data, byteCount) : TMEX.TMBlockIO(_session.SessionHandle, data, byteCount); - // Check to see if the bytes sent matches the value returned - if (nResult != ByteCount) - { - // Throw an access exception - throw new owException(owException.owExceptionFunction.SendBlock, m_oLastID, nResult); - } + // Check to see if the bytes sent matches the value returned + if (result != byteCount) + { + // Throw an access exception + throw new owException(owException.ExceptionFunction.SendBlock, _lastId, result); + } - // Return the result - return nResult; - } + // Return the result + return result; + } - public static short SendBlock(byte[] Data, short ByteCount, bool Reset) - { - short nResult; + public static short ReadBit() + { + // Send the byte and get back what was sent + var result = TMEX.TMTouchBit(_session.SessionHandle, 0xFF); - // Send the block and return the result - if (Reset) - nResult = TMEX.TMBlockStream(m_oSession.SessionHandle, Data, ByteCount); - else - nResult = TMEX.TMBlockIO(m_oSession.SessionHandle, Data, ByteCount); + // Return the result + return result; + } - // Check to see if the bytes sent matches the value returned - if (nResult != ByteCount) - { - // Throw an access exception - throw new owException(owException.owExceptionFunction.SendBlock, m_oLastID, nResult); - } + public static short SendBit(short output) + { + // Send the byte and get back what was sent + var result = TMEX.TMTouchBit(_session.SessionHandle, output); - // Return the result - return nResult; - } + // Check that the value was sent correctly + if (result != output) + { + // Throw an exception + throw new owException(owException.ExceptionFunction.SendBit, _lastId); + } - public static short ReadBit() - { - // Send the byte and get back what was sent - short nResult = TMEX.TMTouchBit(m_oSession.SessionHandle, 0xFF); + // Return the result + return result; + } - // Return the result - return nResult; - } + public static short ReadByte() + { + // Send the byte and get back what was sent + var result = TMEX.TMTouchByte(_session.SessionHandle, 0xFF); - public static short SendBit(short Output) - { - // Send the byte and get back what was sent - short nResult = TMEX.TMTouchBit(m_oSession.SessionHandle, Output); + // Return the result + return result; + } - // Check that the value was sent correctly - if (nResult != Output) - { - // Throw an exception - throw new owException(owException.owExceptionFunction.SendBit, m_oLastID); - } + public static short Reset() + { + // Reset all devices + return TMEX.TMTouchReset(_session.SessionHandle); + } - // Return the result - return nResult; - } + public static short SendByte(short output) + { + // Send the byte and get back what was sent + var result = TMEX.TMTouchByte(_session.SessionHandle, output); - public static short ReadByte() - { - // Send the byte and get back what was sent - short nResult = TMEX.TMTouchByte(m_oSession.SessionHandle, 0xFF); + // Check that the value was sent correctly + if (result != output) + { + // Throw an exception + throw new owException(owException.ExceptionFunction.SendByte, _lastId); + } - // Return the result - return nResult; - } + // Return the result + return result; + } - public static short Reset() - { - // Reset all devices - return TMEX.TMTouchReset(m_oSession.SessionHandle); - } + public static short SetLevel(TMEX.LevelOperation nOperation, TMEX.LevelMode nLevelMode, TMEX.LevelPrime nPrimed) + { + // Set the level + var result = TMEX.TMOneWireLevel(_session.SessionHandle, TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate); - public static short SendByte(short Output) - { - // Send the byte and get back what was sent - short nResult = TMEX.TMTouchByte(m_oSession.SessionHandle, Output); + // Check the result + if (result < 0) + { + // Throw an exception + throw new owException(owException.ExceptionFunction.SetLevel, result); + } - // Check that the value was sent correctly - if (nResult != Output) - { - // Throw an exception - throw new owException(owException.owExceptionFunction.SendByte, m_oLastID); - } - - // Return the result - return nResult; - } - - public static short SetLevel(TMEX.TMOneWireLevelOperation nOperation, TMEX.TMOneWireLevelMode nLevelMode, TMEX.TMOneWireLevelPrime nPrimed) - { - // Set the level - short nResult = TMEX.TMOneWireLevel(m_oSession.SessionHandle, TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); - - // Check the result - if (nResult < 0) - { - // Throw an exception - throw new owException(owException.owExceptionFunction.SetLevel, nResult); - } - - // Return the result - return nResult; - } - - #endregion - } + // Return the result + return result; + } + } } diff --git a/owCRC16.cs b/owCRC16.cs index 6e65ef0..aa1fe49 100644 --- a/owCRC16.cs +++ b/owCRC16.cs @@ -1,16 +1,8 @@ -using System; - namespace OneWireAPI { internal class owCRC16 { - #region CRC lookup table - - private static short[] m_aOddParity = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; - - #endregion - - #region Methods + private static readonly short[] OddParity = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; public static int Calculate(byte[] nData, int iStart, int iEnd) { @@ -19,7 +11,7 @@ namespace OneWireAPI public static int Calculate(byte nData, int iInitialValue) { - byte[] aData = new byte[1]; + var aData = new byte[1]; aData[0] = nData; @@ -28,34 +20,32 @@ namespace OneWireAPI public static int Calculate(byte[] nData, int iStart, int iEnd, int iInitialValue) { - int iIndex; // Loop index - int iCurrentCRC = iInitialValue; // Current CRC accumulator + int index; // Loop index + var currentCrc = iInitialValue; // Current CRC accumulator // Loop over all bytes in the input array - for (iIndex = iStart; iIndex <= iEnd; iIndex++) + for (index = iStart; index <= iEnd; index++) { // Get the current element of data - int iBuffer = nData[iIndex]; + int iBuffer = nData[index]; // Calculate the current CRC for this position - iBuffer = (iBuffer ^ (iCurrentCRC & 0xFF)) & 0xFF; + iBuffer = (iBuffer ^ (currentCrc & 0xFF)) & 0xFF; - iCurrentCRC >>= 8; + currentCrc >>= 8; - if ((m_aOddParity[iBuffer & 0xF] ^ m_aOddParity[iBuffer >> 4]) != 0) - iCurrentCRC ^= 0xC001; + if ((OddParity[iBuffer & 0xF] ^ OddParity[iBuffer >> 4]) != 0) + currentCrc ^= 0xC001; iBuffer <<= 6; - iCurrentCRC ^= iBuffer; + currentCrc ^= iBuffer; iBuffer <<= 1; - iCurrentCRC ^= iBuffer; + currentCrc ^= iBuffer; } // Return the final CRC value - return iCurrentCRC; + return currentCrc; } - - #endregion } } diff --git a/owCRC8.cs b/owCRC8.cs index aa1d624..df75d8e 100644 --- a/owCRC8.cs +++ b/owCRC8.cs @@ -1,76 +1,52 @@ -using System; - namespace OneWireAPI { - internal class owCRC8 - { - #region Member variables + internal class owCRC8 + { + private static byte[] _dataTable; // Lookup table of CRC8 values - private static byte[] m_aDataTable; // Lookup table of CRC8 values + static owCRC8() + { + // Initialize the CRC lookup table + InitializeCrcTable(); + } - #endregion + private static void InitializeCrcTable() + { + // Initialize the size of the lookup table + _dataTable = new byte[256]; - #region Constructor + for (var outer = 0; outer < 256; outer++) + { + var accumulator = outer; // Accumulator value + var crc = 0; // CRC value - static owCRC8() - { - // Initialize the CRC lookup table - InitializeCRCTable(); - } + for (var inner = 0; inner < 8; inner++) + { + if (((accumulator ^ crc) & 0x01) == 0x01) + crc = ((crc ^ 0x18) >> 1) | 0x80; + else + crc = crc >> 1; - #endregion + accumulator = accumulator >> 1; + } - #region Private methods + _dataTable[outer] = (byte) crc; + } + } - private static void InitializeCRCTable() - { - int iAccumulator; // Accumulator value - int iCRC; // CRC value - int iOuter; // Outer loop control - int iInner; // Inner loop control + public static short Calculate(byte[] data, int start, int end) + { + var currentCrc = (short) 0; // Current CRC accumulator - // Initialize the size of the lookup table - m_aDataTable = new byte[256]; + // Loop over all bytes in the input array + for (var index = start; index <= end; index++) + { + // Calculate the current CRC for this position + currentCrc = _dataTable[currentCrc ^ data[index]]; + } - for (iOuter = 0; iOuter < 256; iOuter++) - { - iAccumulator = iOuter; - iCRC = 0; - - for (iInner = 0; iInner < 8; iInner++) - { - if (((iAccumulator ^ iCRC) & 0x01) == 0x01) - iCRC = ((iCRC ^ 0x18) >> 1) | 0x80; - else - iCRC = iCRC >> 1; - - iAccumulator = iAccumulator >> 1; - } - - m_aDataTable[iOuter] = (byte) iCRC; - } - } - - #endregion - - #region Public methods - - public static short Calculate(byte[] nData, int iStart, int iEnd) - { - int iIndex; // Loop index - short nCurrentCRC = 0; // Current CRC accumulator - - // Loop over all bytes in the input array - for (iIndex = iStart; iIndex <= iEnd; iIndex++) - { - // Calculate the current CRC for this position - nCurrentCRC = m_aDataTable[nCurrentCRC ^ nData[iIndex]]; - } - - // Return the final CRC value - return nCurrentCRC; - } - - #endregion - } + // Return the final CRC value + return currentCrc; + } + } } diff --git a/owDevice.cs b/owDevice.cs index cd72ae7..a05e2e9 100644 --- a/owDevice.cs +++ b/owDevice.cs @@ -1,41 +1,27 @@ -using System; - namespace OneWireAPI { - public class owDevice + public class owDevice { - #region Member variables + protected owSession Session; + protected owIdentifier DeviceId; - protected owSession _session; // The current session - protected owIdentifier _deviceID; // The ID of this device - - #endregion - - #region Constructor - - public owDevice(owSession session, short[] rawID) + public owDevice(owSession session, short[] rawId) { // Store the session - _session = session; + Session = session; // Create a new identifier and give it the ID supplied - _deviceID = new owIdentifier(rawID); + DeviceId = new owIdentifier(rawId); } - #endregion - - #region Properties - - public owIdentifier ID + public owIdentifier Id { - get { return _deviceID; } + get { return DeviceId; } } public int Family { - get { return _deviceID.Family; } + get { return DeviceId.Family; } } - - #endregion } } diff --git a/owDeviceFamily10.cs b/owDeviceFamily10.cs index 0b275c7..f4b6c1c 100644 --- a/owDeviceFamily10.cs +++ b/owDeviceFamily10.cs @@ -1,102 +1,90 @@ -using System; - namespace OneWireAPI { - public class owDeviceFamily10 : owDevice - { - #region Constructor + public class owDeviceFamily10 : owDevice + { + public owDeviceFamily10(owSession session, short[] id) + : base(session, id) + { + // Just call the base constructor + } - public owDeviceFamily10(owSession Session, short[] ID) : base(Session, ID) - { - // Just call the base constructor - } + public double GetTemperature() + { + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - #endregion + // Setup for for power delivery after the next byte + owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.StrongPullup, TMEX.LevelPrime.AfterNextByte); - #region Methods + try + { + // Send the byte and start strong pullup + owAdapter.SendByte(0x44); + } + catch + { + // Stop the strong pullup + owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate); - public double GetTemperature() - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - double dCountRemaining; // How many counters remain in the temperature conversion - double dCountPerDegreeC; // How many counters per degree C - int iTemperatureLSB; // The LSB of the temperature - double dTemperature; // double version of the temperature - short nCRC; // Result of the CRC check + // Re-throw the exception + throw; + } - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // Sleep while the data is transfered + System.Threading.Thread.Sleep(1000); - // Setup for for power delivery after the next byte - nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.StrongPullup, TMEX.TMOneWireLevelPrime.AfterNextByte); + // Stop the strong pullup + owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate); - try - { - // Send the byte and start strong pullup - owAdapter.SendByte(0x44); - } - catch - { - // Stop the strong pullup - owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); + // Access the device we want to talk to + owAdapter.Access(); - // Re-throw the exception - throw; - } + // Data buffer to send over the network + var data = new byte[30]; - // Sleep while the data is transfered - System.Threading.Thread.Sleep(1000); + // How many bytes of data to send + short dataCount = 0; - // Stop the strong pullup - nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); + // Set the command to get the temperature from the scatchpad + data[dataCount++] = 0xBE; - // Access the device we want to talk to - owAdapter.Access(); + // Setup the rest of the bytes that we want + for (var i = 0; i < 9; i++) + data[dataCount++] = 0xFF; - // Set the command to get the temperature from the scatchpad - aData[nDataCount++] = 0xBE; + // Send the data block and get data back + owAdapter.SendBlock(data, dataCount); - // Setup the rest of the bytes that we want - for (int i = 0; i < 9; i++) - aData[nDataCount++] = 0xFF; - - // Send the data block and get data back - nResult = owAdapter.SendBlock(aData, nDataCount); + // Calculate the CRC of the first eight bytes of data + var crc = owCRC8.Calculate(data, 1, 8); - // Calculate the CRC of the first eight bytes of data - nCRC = owCRC8.Calculate(aData, 1, 8); + // Check to see if our CRC matches the CRC supplied + if (crc != data[9]) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Check to see if our CRC matches the CRC supplied - if (nCRC != aData[9]) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Get the LSB of the temperature data and divide it by two + var temperatureLsb = data[1] / 2; - // Get the LSB of the temperature data and divide it by two - iTemperatureLSB = aData[1] / 2; + // If the data is negative then flip the bits + if ((data[2] & 0x01) == 0x01) temperatureLsb |= -128; - // If the data is negative then flip the bits - if ((aData[2] & 0x01) == 0x01) iTemperatureLSB |= -128; + // Convert the temperature into a double + var temperature = (double) temperatureLsb; - // Convert the temperature into a double - dTemperature = (double) iTemperatureLSB; + // Get the number of counts remaining + double countRemaining = data[7]; - // Get the number of counts remaining - dCountRemaining = aData[7]; + // Get the number of counts per degree C + double countPerDegreeC = data[8]; - // Get the number of counts per degree C - dCountPerDegreeC = aData[8]; + // Use the "counts remaining" data to calculate the temperaure to greater accuracy + temperature = temperature - 0.25F + (countPerDegreeC - countRemaining) / countPerDegreeC; - // Use the "counts remaining" data to calculate the temperaure to greater accuracy - dTemperature = dTemperature - 0.25F + (dCountPerDegreeC - dCountRemaining) / dCountPerDegreeC; - - // Return the temperature - return dTemperature; - } - - #endregion - } + // Return the temperature + return temperature; + } + } } diff --git a/owDeviceFamily12.cs b/owDeviceFamily12.cs index 774402e..2bfd0fa 100644 --- a/owDeviceFamily12.cs +++ b/owDeviceFamily12.cs @@ -1,199 +1,184 @@ -using System; - namespace OneWireAPI { - public class owDeviceFamily12 : owDevice - { - #region Constants + public class owDeviceFamily12 : owDevice + { + private const byte ChannelAccessCommand = 0xF5; + private const byte WriteStatusCommand = 0x55; + private const byte ReadStatusCommand = 0xAA; - private const byte CHANNEL_ACCESS_COMMAND = 0xF5; // Command value to access a channel - private const byte WRITE_STATUS_COMMAND = 0x55; // Command value to write the status - private const byte READ_STATUS_COMMAND = 0xAA; // Command value to read the status + public owDeviceFamily12(owSession session, short[] id) + : base(session, id) + { + // Just call the base constructor + } - #endregion - - #region Constructor + public bool IsPowered(byte[] state) + { + return ((state[0] & 0x80) == 0x80); + } - public owDeviceFamily12(owSession Session, short[] ID) : base(Session, ID) - { - // Just call the base constructor - } + public bool GetLevel(int channel, byte[] state) + { + if (channel == 0) + return ((state[0] & 0x04) == 0x04); - #endregion + return ((state[0] & 0x08) == 0x08); + } - #region Methods + public bool GetLatchState(int channel, byte[] state) + { + if (channel == 0) + return ((state[1] & 0x20) != 0x20); - public bool IsPowered(byte[] State) - { - return ((State[0] & 0x80) == 0x80); - } + return ((state[1] & 0x40) != 0x40); + } - public bool GetLevel(int Channel, byte[] State) - { - if (Channel == 0) - return ((State[0] & 0x04) == 0x04); - else - return ((State[0] & 0x08) == 0x08); - } + public void SetLatchState(int channel, bool latchState, byte[] state) + { + if (channel == 0) + { + state[1] &= 0xDF; - public bool GetLatchState(int Channel, byte[] State) - { - if (Channel == 0) - { - return ((State[1] & 0x20) != 0x20); - } - else - { - return ((State[1] & 0x40) != 0x40); - } - } + if (!latchState) + state[1] = (byte) (state[1] | 0x20); + } + else + { + state[1] &= 0xBF; - public void SetLatchState(int Channel, bool LatchState, byte[] State) - { - if (Channel == 0) - { - State[1] &= 0xDF; - - if (!LatchState) State[1] = (byte) (State[1] | 0x20); - } - else - { - State[1] &= 0xBF; - - if (!LatchState) State[1] = (byte) (State[1] | 0x40); - } - } + if (!latchState) + state[1] = (byte) (state[1] | 0x40); + } + } - public byte[] ReadDevice() - { - byte[] State = new byte[2]; - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - int iCRCResult; // Result of the CRC calculation - int iMatchCRC; // CRC retrieved from the device + public byte[] ReadDevice() + { + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // Data buffer to send over the network + var data = new byte[30]; - // Set the commmand to execute - aData[nDataCount++] = CHANNEL_ACCESS_COMMAND; + // How many bytes of data to send + short dataCount = 0; - // Set the data - aData[nDataCount++] = 0x55; - aData[nDataCount++] = 0xFF; + // Set the commmand to execute + data[dataCount++] = ChannelAccessCommand; - // Read the info, dummy data and CRC16 - for (int i = 3; i < 7; i++) - aData[nDataCount++] = 0xFF; + // Set the data + data[dataCount++] = 0x55; + data[dataCount++] = 0xFF; - // Send the data - owAdapter.SendBlock(aData, nDataCount); + // Read the info, dummy data and CRC16 + for (var i = 3; i < 7; i++) + data[dataCount++] = 0xFF; - // Calculate the CRC - iCRCResult = owCRC16.Calculate(aData, 0, 4); + // Send the data + owAdapter.SendBlock(data, dataCount); - // Assemble the CRC provided by the device - iMatchCRC = aData[6] << 8; - iMatchCRC |= aData[5]; - iMatchCRC ^= 0xFFFF; + // Calculate the CRC + var crcResult = owCRC16.Calculate(data, 0, 4); - // Make sure the CRC values match - if (iCRCResult != iMatchCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Assemble the CRC provided by the device + var matchCrc = data[6] << 8; + matchCrc |= data[5]; + matchCrc ^= 0xFFFF; - // Store the state data - State[0] = aData[3]; + // Make sure the CRC values match + if (crcResult != matchCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Reset the data count - nDataCount = 0; + var state = new byte[2]; - // Set the command - aData[nDataCount++] = READ_STATUS_COMMAND; + // Store the state data + state[0] = data[3]; - // Set the address to read - aData[nDataCount++] = 7; - aData[nDataCount++] = 0; + // Reset the data count + dataCount = 0; - // Add data for the CRC - for (int i = 3; i < 6; i++) - aData[nDataCount++] = 0xFF; + // Set the command + data[dataCount++] = ReadStatusCommand; - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // Set the address to read + data[dataCount++] = 7; + data[dataCount++] = 0; - // Send the data - owAdapter.SendBlock(aData, nDataCount); + // Add data for the CRC + for (var i = 3; i < 6; i++) + data[dataCount++] = 0xFF; - // Calculate the CRC - iCRCResult = owCRC16.Calculate(aData, 0, 3); + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // Assemble the CRC provided by the device - iMatchCRC = aData[5] << 8; - iMatchCRC |= aData[4]; - iMatchCRC ^= 0xFFFF; + // Send the data + owAdapter.SendBlock(data, dataCount); - // Make sure the CRC values match - if (iCRCResult != iMatchCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Calculate the CRC + crcResult = owCRC16.Calculate(data, 0, 3); - // Store the state data - State[1] = aData[3]; + // Assemble the CRC provided by the device + matchCrc = data[5] << 8; + matchCrc |= data[4]; + matchCrc ^= 0xFFFF; - return State; - } + // Make sure the CRC values match + if (crcResult != matchCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - public void WriteDevice(byte[] State) - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - int iCRCResult; // Result of the CRC calculation - int iMatchCRC; // CRC retrieved from the device + // Store the state data + state[1] = data[3]; - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + return state; + } - // Set the commmand to execute - aData[nDataCount++] = WRITE_STATUS_COMMAND; + public void WriteDevice(byte[] state) + { + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // Set the address - aData[nDataCount++] = 0x07; - aData[nDataCount++] = 0x00; + // Data buffer to send over the network + var data = new byte[30]; - // Add the state - aData[nDataCount++] = State[1]; + // How many bytes of data to send + short dataCount = 0; - // Add bytes for the CRC result - aData[nDataCount++] = 0xFF; - aData[nDataCount++] = 0xFF; + // Set the commmand to execute + data[dataCount++] = WriteStatusCommand; - // Send the data - nResult = owAdapter.SendBlock(aData, nDataCount); + // Set the address + data[dataCount++] = 0x07; + data[dataCount++] = 0x00; - // Calculate the CRC - iCRCResult = owCRC16.Calculate(aData, 0, 3); + // Add the state + data[dataCount++] = state[1]; - // Assemble the CRC provided by the device - iMatchCRC = aData[5] << 8; - iMatchCRC |= aData[4]; - iMatchCRC ^= 0xFFFF; + // Add bytes for the CRC result + data[dataCount++] = 0xFF; + data[dataCount++] = 0xFF; - // Make sure the CRC values match - if (iCRCResult != iMatchCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Send the data + owAdapter.SendBlock(data, dataCount); - return; - } + // Calculate the CRC + var crcResult = owCRC16.Calculate(data, 0, 3); - #endregion - } + // Assemble the CRC provided by the device + var matchCrc = data[5] << 8; + matchCrc |= data[4]; + matchCrc ^= 0xFFFF; + + // Make sure the CRC values match + if (crcResult != matchCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } + } + } } diff --git a/owDeviceFamily1D.cs b/owDeviceFamily1D.cs index f01b803..5301abb 100644 --- a/owDeviceFamily1D.cs +++ b/owDeviceFamily1D.cs @@ -1,76 +1,67 @@ -using System; - namespace OneWireAPI { - public class owDeviceFamily1D : owDevice - { - #region Constructor + public class owDeviceFamily1D : owDevice + { + public owDeviceFamily1D(owSession session, short[] id) + : base(session, id) + { + // Just call the base constructor + } - public owDeviceFamily1D(owSession Session, short[] ID) : base(Session, ID) - { - // Just call the base constructor - } + public uint GetCounter(int counterPage) + { + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - #endregion + // Data buffer to send over the network + var data = new byte[30]; - #region Methods + // How many bytes of data to send + short dataCount = 0; - public uint GetCounter(int CounterPage) - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - int iLastByte; // Address of the last byte in the requested page - uint iCounter = 0; // Counter value - int iCRCResult; // Result of the CRC calculation - int iMatchCRC; // CRC retrieved from the device + // Set the "read memory and counter" command into the data array + data[dataCount++] = 0xA5; - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // Calculate the position of the last byte in the page + var lastByte = (counterPage << 5) + 31; - // Set the "read memory and counter" command into the data array - aData[nDataCount++] = 0xA5; + // Copy the lower byte of the last byte into the data array + data[dataCount++] = (byte) (lastByte & 0xFF); - // Calculate the position of the last byte in the page - iLastByte = (CounterPage << 5) + 31; + // Copy the upper byte of the last byte into the data array + data[dataCount++] = (byte) (lastByte >> 8); - // Copy the lower byte of the last byte into the data array - aData[nDataCount++] = (byte) (iLastByte & 0xFF); + // Add byte for the data byate, counter, zero bits, and CRC16 result + for (var i = 0; i < 11; i++) data[dataCount++] = 0xFF; - // Copy the upper byte of the last byte into the data array - aData[nDataCount++] = (byte) (iLastByte >> 8); + // Send the block of data to the device + owAdapter.SendBlock(data, dataCount); - // Add byte for the data byate, counter, zero bits, and CRC16 result - for (int i = 0; i < 11; i++) aData[nDataCount++] = 0xFF; + // Calculate the CRC based on the data + var crcResult = owCRC16.Calculate(data, 0, 11); - // Send the block of data to the device - nResult = owAdapter.SendBlock(aData, nDataCount); + // Assemble the CRC provided by the device + var matchCrc = data[13] << 8; + matchCrc |= data[12]; + matchCrc ^= 0xFFFF; - // Calculate the CRC based on the data - iCRCResult = owCRC16.Calculate(aData, 0, 11); + // Make sure the CRC values match + if (crcResult != matchCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Assemble the CRC provided by the device - iMatchCRC = aData[13] << 8; - iMatchCRC |= aData[12]; - iMatchCRC ^= 0xFFFF; + uint counter = 0; - // Make sure the CRC values match - if (iCRCResult != iMatchCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Assemble the counter data from the bytes retrieved + for (var i = dataCount - 7; i >= dataCount - 10; i--) + { + counter <<= 8; + counter |= data[i]; + } - // Assemble the counter data from the bytes retrieved - for (int i = nDataCount - 7; i >= nDataCount - 10; i--) - { - iCounter <<= 8; - iCounter |= aData[i]; - } - - return iCounter; - } - - #endregion - } + return counter; + } + } } diff --git a/owDeviceFamily20.cs b/owDeviceFamily20.cs index 8be4b26..687313b 100644 --- a/owDeviceFamily20.cs +++ b/owDeviceFamily20.cs @@ -1,258 +1,242 @@ -using System; - namespace OneWireAPI { - public class owDeviceFamily20 : owDevice - { - #region Member variables + public class owDeviceFamily20 : owDevice + { + private readonly byte[] _control = new byte[16]; - byte[] m_aControl = new byte[16]; + public enum Range : byte + { + Range512 = 0x01, + Range256 = 0x00 + } - #endregion + public enum Resolution : byte + { + EightBits = 0x08, + SixteenBits = 0x00 + } - #region Enumerations + public owDeviceFamily20(owSession session, short[] id) + : base(session, id) + { + } - public enum owDeviceFamily20Range : byte - { - Range_512 = 0x01, - Range_256 = 0x00 - } + public void Initialize() + { + const int startAddress = 0x8; // Starting data page address + const int endAddress = 0x11; // Ending data page address - public enum owDeviceFamily20Resolution : byte - { - EightBits = 0x08, - SixteenBits = 0x00 - } + // Setup the control page + for (var index = 0; index < 8; index += 2) + { + _control[index] = (byte) Resolution.EightBits; + _control[index + 1] = (byte) Range.Range512; + } - #endregion + // Clear the alarm page + for (var index = 8; index < 16; index++) + { + _control[index] = 0; + } - #region Constructor + // Data buffer to send over the network + var data = new byte[30]; - public owDeviceFamily20(owSession Session, short[] ID) : base(Session, ID) - { - } + // How many bytes of data to send + short dataCount = 0; - #endregion + // Set the command into the data array + data[dataCount++] = 0x55; - #region Methods + // Set the starting address of the data to write + data[dataCount++] = startAddress & 0xFF; + data[dataCount++] = (startAddress >> 8) & 0xFF; - public void Initialize() - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - int iIndex; // Loop index - int iStartAddress = 0x8; // Starting data page address - int iEndAddress = 0x11; // Ending data page address - int iCalculatedCRC; // CRC we calculated from sent data - int iSentCRC; // CRC retrieved from the device + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // Setup the control page - for (iIndex = 0; iIndex < 8; iIndex += 2) - { - m_aControl[iIndex] = (byte) owDeviceFamily20Resolution.EightBits; - m_aControl[iIndex + 1] = (byte) owDeviceFamily20Range.Range_512; - } + // Write to the data pages specified + for (var index = startAddress; index <= endAddress; index++) + { + // Copy the control data into our output buffer + data[dataCount++] = _control[index - startAddress]; - // Clear the alarm page - for (iIndex = 8; iIndex < 16; iIndex++) - { - m_aControl[iIndex] = 0; - } + // Add two bytes for the CRC results + data[dataCount++] = 0xFF; + data[dataCount++] = 0xFF; - // Set the command into the data array - aData[nDataCount++] = 0x55; + // Add a byte for the control byte echo + data[dataCount++] = 0xFF; - // Set the starting address of the data to write - aData[nDataCount++] = (byte) (iStartAddress & 0xFF); - aData[nDataCount++] = (byte) ((iStartAddress >> 8) & 0xFF); + // Send the block + owAdapter.SendBlock(data, dataCount); - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // If the check byte doesn't match then throw an exception + if (data[dataCount - 1] != _control[index - startAddress]) + { + // Throw an exception + throw new owException(owException.ExceptionFunction.SendBlock, DeviceId); + } - // Write to the data pages specified - for (iIndex = iStartAddress; iIndex <= iEndAddress; iIndex++) - { - // Copy the control data into our output buffer - aData[nDataCount++] = m_aControl[iIndex - iStartAddress]; + int calculatedCrc; // CRC we calculated from sent data + int sentCrc; // CRC retrieved from the device - // Add two bytes for the CRC results - aData[nDataCount++] = 0xFF; - aData[nDataCount++] = 0xFF; + // Calculate the CRC values + if (index == startAddress) + { + // Calculate the CRC16 of the data sent + calculatedCrc = owCRC16.Calculate(data, 0, 3); - // Add a byte for the control byte echo - aData[nDataCount++] = 0xFF; - - // Send the block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Reconstruct the CRC sent by the device + sentCrc = data[dataCount - 2] << 8; + sentCrc |= data[dataCount - 3]; + sentCrc ^= 0xFFFF; + } + else + { + // Calculate the CRC16 of the data sent + calculatedCrc = owCRC16.Calculate(_control[index - startAddress], index); - // If the check byte doesn't match then throw an exception - if (aData[nDataCount - 1] != m_aControl[iIndex - iStartAddress]) - { - // Throw an exception - throw new owException(owException.owExceptionFunction.SendBlock, _deviceID); - } + // Reconstruct the CRC sent by the device + sentCrc = data[dataCount - 2] << 8; + sentCrc |= data[dataCount - 3]; + sentCrc ^= 0xFFFF; + } - // Calculate the CRC values - if (iIndex == iStartAddress) - { - // Calculate the CRC16 of the data sent - iCalculatedCRC = owCRC16.Calculate(aData, 0, 3); + // If the CRC doesn't match then throw an exception + if (calculatedCrc != sentCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Reconstruct the CRC sent by the device - iSentCRC = aData[nDataCount - 2] << 8; - iSentCRC |= aData[nDataCount - 3]; - iSentCRC ^= 0xFFFF; - } - else - { - // Calculate the CRC16 of the data sent - iCalculatedCRC = owCRC16.Calculate(m_aControl[iIndex - iStartAddress], iIndex); + // Reset the byte count + dataCount = 0; + } + } - // Reconstruct the CRC sent by the device - iSentCRC = aData[nDataCount - 2] << 8; - iSentCRC |= aData[nDataCount - 3]; - iSentCRC ^= 0xFFFF; - } + public double[] GetVoltages() + { + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // If the CRC doesn't match then throw an exception - if (iCalculatedCRC != iSentCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Data buffer to send over the network + var data = new byte[30]; - // Reset the byte count - nDataCount = 0; - } - } + // How many bytes of data to send + short dataCount = 0; - public double[] GetVoltages() - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - int iCalculatedCRC; // CRC we calculated from sent data - int iSentCRC; // CRC retrieved from the device - short nTransmitByte; // Byte of data with the strong pull-up - short nCheckByte = 0; // Byte of data read to see if conversion is done - int iIndex; // Loop index - int iVoltageReadout; // Restructed voltage value from memory - double[] dVoltages = new double[4]; // Voltage values to return + // Set the convert command into the transmit buffer + data[dataCount++] = 0x3C; - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // Set the input mask to get all channels + data[dataCount++] = 0x0F; - // Set the convert command into the transmit buffer - aData[nDataCount++] = 0x3C; + // Set the read-out control to leave things as they are + data[dataCount++] = 0x00; - // Set the input mask to get all channels - aData[nDataCount++] = 0x0F; + // Add two bytes for the CRC results + data[dataCount++] = 0xFF; + data[dataCount++] = 0xFF; - // Set the read-out control to leave things as they are - aData[nDataCount++] = 0x00; + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Add two bytes for the CRC results - aData[nDataCount++] = 0xFF; - aData[nDataCount++] = 0xFF; + // Calculate the CRC based on the transmit buffer + var calculatedCrc = owCRC16.Calculate(data, 0, 2); - // Send the data block - owAdapter.SendBlock(aData, nDataCount); + // Reconstruct the CRC sent by the device + var sentCrc = data[4] << 8; + sentCrc |= data[3]; + sentCrc ^= 0xFFFF; - // Calculate the CRC based on the transmit buffer - iCalculatedCRC = owCRC16.Calculate(aData, 0, 2); + // If the CRC doesn't match then throw an exception + if (calculatedCrc != sentCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Reconstruct the CRC sent by the device - iSentCRC = aData[4] << 8; - iSentCRC |= aData[3]; - iSentCRC ^= 0xFFFF; + // Setup for for power delivery after the next byte + owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.StrongPullup, TMEX.LevelPrime.AfterNextByte); - // If the CRC doesn't match then throw an exception - if (iCalculatedCRC != iSentCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + var nTransmitByte = (short) ((dataCount - 1) & 0x1F); - // Setup for for power delivery after the next byte - nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.StrongPullup, TMEX.TMOneWireLevelPrime.AfterNextByte); + try + { + // Send the byte and start strong pullup + owAdapter.SendByte(nTransmitByte); + } + catch + { + // Stop the strong pullup + owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate); - nTransmitByte = (short) ((nDataCount - 1) & 0x1F); + // Re-throw the exception + throw; + } - try - { - // Send the byte and start strong pullup - owAdapter.SendByte(nTransmitByte); - } - catch - { - // Stop the strong pullup - owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); + // Sleep while the data is transfered + System.Threading.Thread.Sleep(6); - // Re-throw the exception - throw; - } + // Stop the strong pullup + owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate); - // Sleep while the data is transfered - System.Threading.Thread.Sleep(6); + // Read data to see if the conversion is over + owAdapter.ReadByte(); - // Stop the strong pullup - nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // Read data to see if the conversion is over - nCheckByte = owAdapter.ReadByte(); + // Reinitialize the data count + dataCount = 0; - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // Set the read command into the transmit buffer + data[dataCount++] = 0xAA; - // Reinitialize the data count - nDataCount = 0; + // Set the address to get the conversion results + data[dataCount++] = 0x00; + data[dataCount++] = 0x00; - // Set the read command into the transmit buffer - aData[nDataCount++] = 0xAA; + // Add 10 bytes to be read - 8 for the data and 2 for the CRC + for (var index = 0; index < 10; index++) + data[dataCount++] = 0xFF; - // Set the address to get the conversion results - aData[nDataCount++] = 0x00; - aData[nDataCount++] = 0x00; + // Send the block to the device + owAdapter.SendBlock(data, dataCount); - // Add 10 bytes to be read - 8 for the data and 2 for the CRC - for (iIndex = 0; iIndex < 10; iIndex++) - aData[nDataCount++] = 0xFF; + // Calculate the CRC of the transmitted data + calculatedCrc = owCRC16.Calculate(data, 0, 10); - // Send the block to the device - nResult = owAdapter.SendBlock(aData, nDataCount); + // Reconstruct the CRC sent by the device + sentCrc = data[dataCount - 1] << 8; + sentCrc |= data[dataCount - 2]; + sentCrc ^= 0xFFFF; - // Calculate the CRC of the transmitted data - iCalculatedCRC = owCRC16.Calculate(aData, 0, 10); + // If the CRC doesn't match then throw an exception + if (calculatedCrc != sentCrc) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Reconstruct the CRC sent by the device - iSentCRC = aData[nDataCount - 1] << 8; - iSentCRC |= aData[nDataCount - 2]; - iSentCRC ^= 0xFFFF; + // Voltage values to return + var voltages = new double[4]; - // If the CRC doesn't match then throw an exception - if (iCalculatedCRC != iSentCRC) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Convert the data into a double + for (var index = 3; index < 11; index += 2) + { + // Reconstruct the two bytes into the 16-bit values + var iVoltageReadout = ((data[index + 1] << 8) | data[index]) & 0x0000FFFF; - // Convert the data into a double - for (iIndex = 3; iIndex < 11; iIndex += 2) - { - // Reconstruct the two bytes into the 16-bit values - iVoltageReadout = ((aData[iIndex + 1] << 8) | aData[iIndex]) & 0x0000FFFF; + // Figure out the percentage of the top voltage is present + voltages[(index - 3) / 2] = iVoltageReadout / 65535.0; - // Figure out the percentage of the top voltage is present - dVoltages[(iIndex - 3) / 2] = iVoltageReadout / 65535.0; + // Apply the percentage to the maximum voltage range + voltages[(index - 3) / 2] *= ((_control[(index - 3) + 1] & 0x01) == 0x01 ? 5.12 : 2.56); + } - // Apply the percentage to the maximum voltage range - dVoltages[(iIndex - 3) / 2] *= ((m_aControl[(iIndex - 3) + 1] & 0x01) == 0x01 ? 5.12 : 2.56); - } - - return dVoltages; - } - - #endregion - } + return voltages; + } + } } diff --git a/owDeviceFamily26.cs b/owDeviceFamily26.cs index 013dca4..3e0a505 100644 --- a/owDeviceFamily26.cs +++ b/owDeviceFamily26.cs @@ -1,277 +1,262 @@ -using System; - namespace OneWireAPI { - public class owDeviceFamily26 : owDevice - { - #region Constructor + public class owDeviceFamily26 : owDevice + { + public owDeviceFamily26(owSession session, short[] id) + : base(session, id) + { + // Just call the base constructor + } - public owDeviceFamily26(owSession Session, short[] ID) : base(Session, ID) - { - // Just call the base constructor - } + public enum VoltageType : short + { + Supply, + Output + } - #endregion + private double GetVoltage(VoltageType type) + { + short busy; - #region Methods + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - public enum VoltageType : short - { - Supply, - Output - } + // Data buffer to send over the network + var data = new byte[30]; - private double GetVoltage(VoltageType Type) - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - short nCRC; // Result of the CRC check - int iIndex; - short nBusy; - double dVoltage; + // How many bytes of data to send + short dataCount = 0; - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); - - // Set the command to recall the status/configuration page to the scratchpad - aData[nDataCount++] = 0xB8; + // Set the command to recall the status/configuration page to the scratchpad + data[dataCount++] = 0xB8; - // Set the page number to recall - aData[nDataCount++] = 0x00; + // Set the page number to recall + data[dataCount++] = 0x00; - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Clear the data count - nDataCount = 0; + // Clear the data count + dataCount = 0; - // Access the device we want to talk to - owAdapter.Access(); + // Access the device we want to talk to + owAdapter.Access(); - // Set the command to read the scratchpad - aData[nDataCount++] = 0xBE; + // Set the command to read the scratchpad + data[dataCount++] = 0xBE; - // Set the page number to read - aData[nDataCount++] = 0x00; + // Set the page number to read + data[dataCount++] = 0x00; - // Add 9 bytes to be read - 8 for the data and 1 for the CRC - for (iIndex = 0; iIndex < 9; iIndex++) - aData[nDataCount++] = 0xFF; + // Add 9 bytes to be read - 8 for the data and 1 for the CRC + for (var index = 0; index < 9; index++) + data[dataCount++] = 0xFF; - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Calculate the CRC of the scratchpad data - nCRC = owCRC8.Calculate(aData, 2, 9); + // Calculate the CRC of the scratchpad data + var crc = owCRC8.Calculate(data, 2, 9); - // If the CRC doesn't match then throw an exception - if (nCRC != aData[10]) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // If the CRC doesn't match then throw an exception + if (crc != data[10]) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // TODO - Check if we really need to change the input selector - if (true) - { - // Access the device we want to talk to - owAdapter.Access(); + // TODO - Check if we really need to change the input selector + if (true) + { + // Access the device we want to talk to + owAdapter.Access(); - // Reset the data count - nDataCount = 0; + // Reset the data count + dataCount = 0; - // Set the command to write the scratchpad - aData[nDataCount++] = 0x4E; + // Set the command to write the scratchpad + data[dataCount++] = 0x4E; - // Set the page number to write - aData[nDataCount++] = 0x00; + // Set the page number to write + data[dataCount++] = 0x00; - // Set or clear the AD bit based on the type requested - if (Type == VoltageType.Supply) - aData[nDataCount++] = (byte) (aData[2] | 0x08); - else - aData[nDataCount++] = (byte) (aData[2] & 0xF7); + // Set or clear the AD bit based on the type requested + if (type == VoltageType.Supply) + data[dataCount++] = (byte) (data[2] | 0x08); + else + data[dataCount++] = (byte) (data[2] & 0xF7); - // Move the existing data down in the array - for (iIndex = 0; iIndex < 7; iIndex++) - aData[nDataCount++] = aData[iIndex + 4]; + // Move the existing data down in the array + for (var index = 0; index < 7; index++) + data[dataCount++] = data[index + 4]; - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Reset the data count - nDataCount = 0; - - // Access the device we want to talk to - owAdapter.Access(); - - // Set the command to copy the scratchpad - aData[nDataCount++] = 0x48; - - // Set the page number to copy to - aData[nDataCount++] = 0x00; - - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); - - // Loop until the data copy is complete - do - { - nBusy = owAdapter.ReadByte(); - } - while (nBusy == 0); - } + // Reset the data count + dataCount = 0; - // Access the device we want to talk to - owAdapter.Access(); + // Access the device we want to talk to + owAdapter.Access(); - // Send the voltage conversion command - owAdapter.SendByte(0xB4); + // Set the command to copy the scratchpad + data[dataCount++] = 0x48; - // Loop until conversion is complete - do - { - nBusy = owAdapter.ReadByte(); - } - while (nBusy == 0); + // Set the page number to copy to + data[dataCount++] = 0x00; - // Clear the data count - nDataCount = 0; + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Set the command to recall the status/configuration page to the scratchpad - aData[nDataCount++] = 0xB8; + // Loop until the data copy is complete + do + { + busy = owAdapter.ReadByte(); + } + while (busy == 0); + } - // Set the page number to recall - aData[nDataCount++] = 0x00; + // Access the device we want to talk to + owAdapter.Access(); - // Access the device we want to talk to - owAdapter.Access(); + // Send the voltage conversion command + owAdapter.SendByte(0xB4); - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Loop until conversion is complete + do + { + busy = owAdapter.ReadByte(); + } + while (busy == 0); - // Clear the data count - nDataCount = 0; + // Clear the data count + dataCount = 0; - // Access the device we want to talk to - owAdapter.Access(); + // Set the command to recall the status/configuration page to the scratchpad + data[dataCount++] = 0xB8; - // Set the command to read the scratchpad - aData[nDataCount++] = 0xBE; + // Set the page number to recall + data[dataCount++] = 0x00; - // Set the page number to read - aData[nDataCount++] = 0x00; + // Access the device we want to talk to + owAdapter.Access(); - // Add 9 bytes to be read - 8 for the data and 1 for the CRC - for (iIndex = 0; iIndex < 9; iIndex++) - aData[nDataCount++] = 0xFF; + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Clear the data count + dataCount = 0; - // Calculate the CRC of the scratchpad data - nCRC = owCRC8.Calculate(aData, 2, 9); + // Access the device we want to talk to + owAdapter.Access(); - // If the CRC doesn't match then throw an exception - if (nCRC != aData[10]) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } - - // Assemble the voltage data - dVoltage = (double) ((aData[6] << 8) | aData[5]); - - return dVoltage / 100; - } + // Set the command to read the scratchpad + data[dataCount++] = 0xBE; - public double GetSupplyVoltage() - { - return GetVoltage(VoltageType.Supply); - } + // Set the page number to read + data[dataCount++] = 0x00; - public double GetOutputVoltage() - { + // Add 9 bytes to be read - 8 for the data and 1 for the CRC + for (var index = 0; index < 9; index++) + data[dataCount++] = 0xFF; - return GetVoltage(VoltageType.Output); - } + // Send the data block + owAdapter.SendBlock(data, dataCount); - public double GetTemperature() - { - short nResult; // Result of method calls - byte[] aData = new byte[30]; // Data buffer to send over the network - short nDataCount = 0; // How many bytes of data to send - short nCRC; // Result of the CRC check - int iTemperatureLSB; // The LSB of the temperature data - int iTemperatureMSB; // The MSB of the temperature data - int iTemperature; // Complete temperature data - double dTemperature; // double version of the temperature + // Calculate the CRC of the scratchpad data + crc = owCRC8.Calculate(data, 2, 9); - // Select and access the ID of the device we want to talk to - owAdapter.Select(_deviceID); + // If the CRC doesn't match then throw an exception + if (crc != data[10]) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } - // Send the conversion command byte - owAdapter.SendByte(0x44); + // Assemble the voltage data + var dVoltage = (double) ((data[6] << 8) | data[5]); - // Sleep while the data is converted - System.Threading.Thread.Sleep(10); + return dVoltage / 100; + } - // Access the device we want to talk to - owAdapter.Access(); + public double GetSupplyVoltage() + { + return GetVoltage(VoltageType.Supply); + } - // Set the command to recall the status/configuration page to the scratchpad - aData[nDataCount++] = 0xB8; + public double GetOutputVoltage() + { - // Set the page number to recall - aData[nDataCount++] = 0x00; + return GetVoltage(VoltageType.Output); + } - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + public double GetTemperature() + { + // Select and access the ID of the device we want to talk to + owAdapter.Select(DeviceId); - // Clear the data count - nDataCount = 0; + // Send the conversion command byte + owAdapter.SendByte(0x44); - // Access the device we want to talk to - owAdapter.Access(); + // Sleep while the data is converted + System.Threading.Thread.Sleep(10); - // Set the command to read the scratchpad - aData[nDataCount++] = 0xBE; + // Access the device we want to talk to + owAdapter.Access(); - // Set the page number to read - aData[nDataCount++] = 0x00; + // Data buffer to send over the network + var data = new byte[30]; - // Add 9 bytes to be read - 8 for the data and 1 for the CRC - for (int iIndex = 0; iIndex < 9; iIndex++) - aData[nDataCount++] = 0xFF; + // How many bytes of data to send + short dataCount = 0; - // Send the data block - nResult = owAdapter.SendBlock(aData, nDataCount); + // Set the command to recall the status/configuration page to the scratchpad + data[dataCount++] = 0xB8; - // Calculate the CRC of the scratchpad data - nCRC = owCRC8.Calculate(aData, 2, 9); + // Set the page number to recall + data[dataCount++] = 0x00; - // If the CRC doesn't match then throw an exception - if (nCRC != aData[10]) - { - // Throw a CRC exception - throw new owException(owException.owExceptionFunction.CRC, _deviceID); - } + // Send the data block + owAdapter.SendBlock(data, dataCount); - // Get the two bytes of temperature data - iTemperatureLSB = aData[3]; - iTemperatureMSB = aData[4]; + // Clear the data count + dataCount = 0; - // Shift the data into the right order - iTemperature = ((iTemperatureMSB << 8) | iTemperatureLSB) >> 3; + // Access the device we want to talk to + owAdapter.Access(); - // Figure out the temperature - dTemperature = iTemperature * 0.03125F; + // Set the command to read the scratchpad + data[dataCount++] = 0xBE; - // Return the temperature - return dTemperature; - } + // Set the page number to read + data[dataCount++] = 0x00; - #endregion - } + // Add 9 bytes to be read - 8 for the data and 1 for the CRC + for (var iIndex = 0; iIndex < 9; iIndex++) + data[dataCount++] = 0xFF; + + // Send the data block + owAdapter.SendBlock(data, dataCount); + + // Calculate the CRC of the scratchpad data + var crc = owCRC8.Calculate(data, 2, 9); + + // If the CRC doesn't match then throw an exception + if (crc != data[10]) + { + // Throw a CRC exception + throw new owException(owException.ExceptionFunction.Crc, DeviceId); + } + + // Get the two bytes of temperature data + int temperatureLsb = data[3]; + int temperatureMsb = data[4]; + + // Shift the data into the right order + var iTemperature = ((temperatureMsb << 8) | temperatureLsb) >> 3; + + // Return the temperature + return iTemperature * 0.03125F; + } + } } diff --git a/owDeviceFamilyFF.cs b/owDeviceFamilyFF.cs index f19db3b..b3b4995 100644 --- a/owDeviceFamilyFF.cs +++ b/owDeviceFamilyFF.cs @@ -1,172 +1,172 @@ -using System; - namespace OneWireAPI { - public class owDeviceFamilyFF : owDevice - { - #region Member variables + public class owDeviceFamilyFF : owDevice + { + private int _width = 20; + private int _height = 4; - private int m_iWidth = 20; - private int m_iHeight = 4; + public owDeviceFamilyFF(owSession session, short[] id) + : base(session, id) + { + // Just call the base constructor + } - #endregion + public void SetSize(int width, int height) + { + _width = width; + _height = height; + } - #region Constructor + public void SetBackLight(bool state) + { + // Select the device + owAdapter.Select(DeviceId); - public owDeviceFamilyFF(owSession Session, short[] ID) : base(Session, ID) - { - // Just call the base constructor - } + // Set the state of the backlight + owAdapter.SendByte((short) (state ? 0x8 : 0x7)); + } - #endregion - - #region Methods - - public void SetBackLight(bool State) - { - // Select the device - owAdapter.Select(_deviceID); - - // Set the state of the backlight - owAdapter.SendByte((short) (State ? 0x8 : 0x7)); - } - - public void SetText(string Text) - { - string[] sLines = null; // Array of lines - int iLine = 1; // Line number + public void SetText(string text) + { + // Line number + var line = 1; // Replace any CRLF pairs with just a newline - Text = Text.Replace("\r\n", "\n"); - - // Split the input string at any newlines - sLines = Text.Split("\n".ToCharArray(), m_iHeight); + text = text.Replace("\r\n", "\n"); - // Loop over each line - foreach (string sLine in sLines) - { - // Set the text of this line - SetText(sLine, iLine++); - } - } + // Split the input string at any newlines + var sLines = text.Split("\n".ToCharArray(), _height); - public void SetText(string Text, int Line) - { - short nMemoryPosition = 0x00; // Position at which to write the new string data - string sSendData = ""; // String data to send - byte[] baData; // Byte array of data to send - short nDataCount = 0; // Amount of data to send + // Loop over each line + foreach (var sLine in sLines) + { + // Set the text of this line + SetText(sLine, line++); + } + } - // Figure out the initial memory position based on the line number - switch (Line) - { - case 1: - nMemoryPosition = 0x00; - break; + public void SetText(string text, int line) + { + // Position at which to write the new string data + short memoryPosition = 0x00; - case 2: - nMemoryPosition = 0x40; - break; + // String data to send + string sendData; - case 3: - nMemoryPosition = 0x14; - break; + // Byte array of data to send + byte[] data; - case 4: - nMemoryPosition = 0x54; - break; - } + // Amount of data to send + short dataCount = 0; - // Pad the text to the right width - Text = Text.PadRight(m_iWidth); + // Figure out the initial memory position based on the line number + switch (line) + { + case 1: + memoryPosition = 0x00; + break; - // The scratchpad is only 16 bytes long so we need to split it up - if (m_iWidth > 16) - { - // Select the device - owAdapter.Select(_deviceID); + case 2: + memoryPosition = 0x40; + break; - // Set the data block to just the first 16 characters - sSendData = Text.Substring(0, 16); + case 3: + memoryPosition = 0x14; + break; - // Initialize the data array - baData = new byte[18]; + case 4: + memoryPosition = 0x54; + break; + } - // Set the command to write to the scratchpad - baData[nDataCount++] = 0x4E; + // Pad the text to the right width + text = text.PadRight(_width); - // Set the memory position - baData[nDataCount++] = (byte) nMemoryPosition; + // The scratchpad is only 16 bytes long so we need to split it up + if (_width > 16) + { + // Select the device + owAdapter.Select(DeviceId); - // Add the text data to the data - foreach (byte bChar in System.Text.Encoding.Default.GetBytes(sSendData)) - baData[nDataCount++] = bChar; + // Set the data block to just the first 16 characters + sendData = text.Substring(0, 16); - // Set the block - owAdapter.SendBlock(baData, nDataCount); + // Initialize the data array + data = new byte[18]; - // Select the device - owAdapter.Select(_deviceID); + // Set the command to write to the scratchpad + data[dataCount++] = 0x4E; - // Send the scratchpad data to the LCD - owAdapter.SendByte(0x48); + // Set the memory position + data[dataCount++] = (byte) memoryPosition; - // Reset the device - owAdapter.Reset(); + // Add the text data to the data + foreach (var bChar in System.Text.Encoding.Default.GetBytes(sendData)) + data[dataCount++] = bChar; - // Increment the memory position - nMemoryPosition += 16; + // Set the block + owAdapter.SendBlock(data, dataCount); - // Set the data to the rest of the line - sSendData = Text.Substring(16, m_iWidth - 16); - } - else - { - // Just set the data string to whatever was passed in - sSendData = Text; - } + // Select the device + owAdapter.Select(DeviceId); - // Select the device - owAdapter.Select(_deviceID); + // Send the scratchpad data to the LCD + owAdapter.SendByte(0x48); - // Initialize the data array - baData = new byte[18]; + // Reset the device + owAdapter.Reset(); - // Reset the data count - nDataCount = 0; + // Increment the memory position + memoryPosition += 16; - // Set the command to write to the scratchpad - baData[nDataCount++] = 0x4E; + // Set the data to the rest of the line + sendData = text.Substring(16, _width - 16); + } + else + { + // Just set the data string to whatever was passed in + sendData = text; + } - // Set the memory position - baData[nDataCount++] = (byte) nMemoryPosition; + // Select the device + owAdapter.Select(DeviceId); - // Add the text data to the data - foreach (byte bChar in System.Text.Encoding.Default.GetBytes(sSendData)) - baData[nDataCount++] = bChar; + // Initialize the data array + data = new byte[18]; - // Set the block - owAdapter.SendBlock(baData, nDataCount); + // Reset the data count + dataCount = 0; - // Select the device - owAdapter.Select(_deviceID); + // Set the command to write to the scratchpad + data[dataCount++] = 0x4E; - // Send the scratchpad data to the LCD - owAdapter.SendByte(0x48); + // Set the memory position + data[dataCount++] = (byte) memoryPosition; - // Reset the device - owAdapter.Reset(); - } + // Add the text data to the data + foreach (var bChar in System.Text.Encoding.Default.GetBytes(sendData)) + data[dataCount++] = bChar; - public void Clear() - { - // Select the device - owAdapter.Select(_deviceID); + // Set the block + owAdapter.SendBlock(data, dataCount); - // Clear the display - owAdapter.SendByte(0x49); - } + // Select the device + owAdapter.Select(DeviceId); - #endregion - } + // Send the scratchpad data to the LCD + owAdapter.SendByte(0x48); + + // Reset the device + owAdapter.Reset(); + } + + public void Clear() + { + // Select the device + owAdapter.Select(DeviceId); + + // Clear the display + owAdapter.SendByte(0x49); + } + } } diff --git a/owException.cs b/owException.cs index c4700a7..4eb1727 100644 --- a/owException.cs +++ b/owException.cs @@ -5,12 +5,10 @@ namespace OneWireAPI [Serializable] public class owException : Exception { - #region Enumerations - - public enum owExceptionFunction + public enum ExceptionFunction { Access, - CRC, + Crc, ReadBit, ReadByte, Select, @@ -20,19 +18,11 @@ namespace OneWireAPI SetLevel } - #endregion - - #region Private member variables - private readonly int _errorNumber; - private readonly owExceptionFunction _errorFunction; - private readonly owIdentifier _deviceID; + private readonly ExceptionFunction _errorFunction; + private readonly owIdentifier _deviceId; - #endregion - - #region Constructors - - public owException(owExceptionFunction function, int number) + public owException(ExceptionFunction function, int number) { // Store the exception function _errorFunction = function; @@ -41,37 +31,33 @@ namespace OneWireAPI _errorNumber = number; } - public owException(owExceptionFunction function, owIdentifier deviceID) + public owException(ExceptionFunction function, owIdentifier deviceId) { // Store the exception function _errorFunction = function; // Store the device ID - _deviceID = deviceID; + _deviceId = deviceId; } - public owException(owExceptionFunction function, owIdentifier deviceID, int number) + public owException(ExceptionFunction function, owIdentifier deviceId, int number) { // Store the exception function _errorFunction = function; // Store the device ID - _deviceID = deviceID; + _deviceId = deviceId; // Store the exception number _errorNumber = number; } - #endregion - - #region Properties - - public owIdentifier DeviceID + public owIdentifier DeviceId { - get { return _deviceID; } + get { return _deviceId; } } - public owExceptionFunction Function + public ExceptionFunction Function { get { return _errorFunction; } } @@ -82,16 +68,26 @@ namespace OneWireAPI { switch (_errorFunction) { - case owExceptionFunction.Access: return "Unable to access device"; - case owExceptionFunction.CRC: return "CRC mismatch"; - case owExceptionFunction.ReadBit: return "Error reading bit"; - case owExceptionFunction.ReadByte: return "Error reading byte"; - case owExceptionFunction.Select: return "Unable to select device"; - case owExceptionFunction.SendBit: return "Error sending bit"; - case owExceptionFunction.SendBlock: return "Error sending block"; - case owExceptionFunction.SendByte: return "Error sending byte"; - case owExceptionFunction.SetLevel: return "Error setting level"; - default: return "Unknown error in function" + _errorFunction; + case ExceptionFunction.Access: + return "Unable to access device"; + case ExceptionFunction.Crc: + return "CRC mismatch"; + case ExceptionFunction.ReadBit: + return "Error reading bit"; + case ExceptionFunction.ReadByte: + return "Error reading byte"; + case ExceptionFunction.Select: + return "Unable to select device"; + case ExceptionFunction.SendBit: + return "Error sending bit"; + case ExceptionFunction.SendBlock: + return "Error sending block"; + case ExceptionFunction.SendByte: + return "Error sending byte"; + case ExceptionFunction.SetLevel: + return "Error setting level"; + default: + return "Unknown error in function" + _errorFunction; } } } @@ -100,7 +96,5 @@ namespace OneWireAPI { get { return _errorNumber; } } - - #endregion } } diff --git a/owIdentifer.cs b/owIdentifer.cs index 85e0a2c..d6d53fd 100644 --- a/owIdentifer.cs +++ b/owIdentifer.cs @@ -1,80 +1,65 @@ -using System; using System.Text; namespace OneWireAPI { - public class owIdentifier + public class owIdentifier { - #region Member variables - - private readonly short[] _rawID; // The raw ID array + private readonly short[] _rawId; // The raw ID array private readonly string _friendlyName; // Friendly display name private readonly int _familyCode; // Family code - #endregion - - #region Constructors - public owIdentifier() { // Create a blank ID - _rawID = new short[8]; + _rawId = new short[8]; } - public owIdentifier(byte[] deviceID) + public owIdentifier(byte[] deviceId) { // Create a blank ID - _rawID = new short[8]; + _rawId = new short[8]; // Copy the byte array to the short array - for (int i = 0; i < deviceID.Length; i++) - _rawID[i] = deviceID[i]; + for (var i = 0; i < deviceId.Length; i++) + _rawId[i] = deviceId[i]; // Get the friendly name - _friendlyName = ConvertToString(_rawID); + _friendlyName = ConvertToString(_rawId); // Get the family code - _familyCode = _rawID[0]; + _familyCode = _rawId[0]; } - public owIdentifier(short[] deviceID) + public owIdentifier(short[] deviceId) { // Store the ID supplied - _rawID = deviceID; + _rawId = deviceId; // Get the friendly name - _friendlyName = ConvertToString(_rawID); + _friendlyName = ConvertToString(_rawId); // Get the family code - _familyCode = _rawID[0]; + _familyCode = _rawId[0]; } - #endregion - - #region Private methods - - private static string ConvertToString(short[] rawID) + private static string ConvertToString(short[] rawId) { - StringBuilder friendlyID = new StringBuilder(); + var friendlyId = new StringBuilder(); // Loop backwards over the ID array - for (int iIndex = rawID.Length - 1; iIndex >= 0; iIndex--) + for (var iIndex = rawId.Length - 1; iIndex >= 0; iIndex--) { // Convert the short value into a hex string and append it to the ID string - friendlyID.AppendFormat("{0:X2}", rawID[iIndex]); + friendlyId.AppendFormat("{0:X2}", rawId[iIndex]); } // Return the ID string - return friendlyID.ToString(); + return friendlyId.ToString(); } - #endregion - - #region Properties - - public short[] RawID + public short[] RawId { - get { return _rawID; } + get { return _rawId; } } public string Name @@ -87,15 +72,9 @@ namespace OneWireAPI get { return _familyCode; } } - #endregion - - #region Methods - public override string ToString() { return _friendlyName; } - - #endregion } } diff --git a/owNetwork.cs b/owNetwork.cs index b098cfd..3f398ef 100644 --- a/owNetwork.cs +++ b/owNetwork.cs @@ -1,95 +1,76 @@ -using System; using System.Collections.Generic; namespace OneWireAPI { public class owNetwork { - #region Member variables - private owSession _session; // Current session private Dictionary _deviceList; // List of current devices - #endregion - - #region Constructor - - public owNetwork(owSession Session) + public owNetwork(owSession session) { - _session = Session; + _session = session; _deviceList = new Dictionary(); } - #endregion - - #region Delegates - public delegate void DeviceEventDelegate(owDevice device); - #endregion - - #region Events - public event DeviceEventDelegate DeviceAdded; - #endregion - - #region Private methods - private void LoadDevices() { - owDevice device; // Current device object - // Get the first device on the network - short nResult = TMEX.TMFirst(_session.SessionHandle, _session.StateBuffer); + var nResult = TMEX.TMFirst(_session.SessionHandle, _session.StateBuffer); // Keep looping while we get good device data while (nResult == 1) { // Create a new device ID buffer - short[] nROM = new short[8]; + var id = new short[8]; // Get the ROM from the device - nResult = TMEX.TMRom(_session.SessionHandle, _session.StateBuffer, nROM); + nResult = TMEX.TMRom(_session.SessionHandle, _session.StateBuffer, id); // If the ROM was read correctly then add the device to the list if (nResult == 1) { // Get the deviceID - owIdentifier deviceID = new owIdentifier(nROM); + var deviceId = new owIdentifier(id); // Create a new device object - switch (deviceID.Family) + owDevice device; + + switch (deviceId.Family) { case 0x10: - device = new owDeviceFamily10(_session, nROM); + device = new owDeviceFamily10(_session, id); break; case 0x1D: - device = new owDeviceFamily1D(_session, nROM); + device = new owDeviceFamily1D(_session, id); break; case 0x20: - device = new owDeviceFamily20(_session, nROM); + device = new owDeviceFamily20(_session, id); break; case 0x26: - device = new owDeviceFamily26(_session, nROM); + device = new owDeviceFamily26(_session, id); break; case 0x12: - device = new owDeviceFamily12(_session, nROM); + device = new owDeviceFamily12(_session, id); break; case 0xFF: - device = new owDeviceFamilyFF(_session, nROM); + device = new owDeviceFamilyFF(_session, id); break; default: - device = new owDevice(_session, nROM); + device = new owDevice(_session, id); break; } // Check if we've seen this device before - if (!_deviceList.ContainsKey(device.ID.Name)) + if (!_deviceList.ContainsKey(device.Id.Name)) { // Add the device to the device list - _deviceList[device.ID.Name] = device; + _deviceList[device.Id.Name] = device; // Raise the device added event if (DeviceAdded != null) @@ -102,19 +83,11 @@ namespace OneWireAPI } } - #endregion - - #region Properties - public Dictionary Devices { get { return _deviceList; } } - #endregion - - #region Public methods - public void Initialize() { // Load the device list @@ -130,7 +103,5 @@ namespace OneWireAPI // Get rid of the session _session = null; } - - #endregion } } diff --git a/owSession.cs b/owSession.cs index a53027f..ad25690 100644 --- a/owSession.cs +++ b/owSession.cs @@ -1,13 +1,10 @@ using Common.Debug; using System; -using System.Threading; namespace OneWireAPI { public class owSession { - #region Member variables - private int _sessionHandle; // Session handle private owNetwork _network; // Network object @@ -15,35 +12,27 @@ namespace OneWireAPI private readonly short _portType; // Port type private readonly byte[] _stateBuffer; // Global state buffer - #endregion - - #region Constructor - public owSession() { // Create the global state buffer - _stateBuffer = new byte[(int) TMEX.TMStateBufferSize.NoEPROMWriting]; + _stateBuffer = new byte[(int) TMEX.StateBufferSize.NoEpromWriting]; // Get the default port number and type from the system - short result = TMEX.TMReadDefaultPort(out _portNumber, out _portType); + var result = TMEX.TMReadDefaultPort(out _portNumber, out _portType); Tracer.WriteLine("TMReadDefaultPort - Return: {0}, Port Number: {1}, Port Type: {2}", result, _portNumber, _portType); } - public owSession(short PortNumber, short PortType) + public owSession(short portNumber, short portType) { // Create the global state buffer - _stateBuffer = new byte[(int) TMEX.TMStateBufferSize.NoEPROMWriting]; + _stateBuffer = new byte[(int) TMEX.StateBufferSize.NoEpromWriting]; // Store the port number and type specified - _portNumber = PortNumber; - _portType = PortType; + _portNumber = portNumber; + _portType = portType; } - #endregion - - #region Properties - public short PortNumber { get { return _portNumber; } @@ -69,23 +58,19 @@ namespace OneWireAPI get { return _stateBuffer; } } - #endregion - - #region Methods - public bool Acquire() { // Create a byte array to hold the version information - byte[] version = new byte[80]; + var version = new byte[80]; // Get the version TMEX.Get_Version(version); // Decode the version - string sVersion = System.Text.Encoding.Default.GetString(version, 0, version.Length); + var sVersion = System.Text.Encoding.Default.GetString(version, 0, version.Length); // Strip everything up to the first null character - sVersion = sVersion.Substring(0, sVersion.IndexOf("\0")); + sVersion = sVersion.Substring(0, sVersion.IndexOf("\0", StringComparison.Ordinal)); Tracer.WriteLine("Version: {0}", sVersion); @@ -101,7 +86,7 @@ namespace OneWireAPI return false; // Setup the port for the current session - short result = TMEX.TMSetup(_sessionHandle); + var result = TMEX.TMSetup(_sessionHandle); Tracer.WriteLine("TMSetup - Return: {0}", result); @@ -138,7 +123,7 @@ namespace OneWireAPI } // Close the session - short result = TMEX.TMClose(_sessionHandle); + var result = TMEX.TMClose(_sessionHandle); Tracer.WriteLine("TMClose - Return: {0}", result); @@ -150,7 +135,5 @@ namespace OneWireAPI // Clear the session variable _sessionHandle = 0; } - - #endregion } }