Code modernization

This commit is contained in:
2015-01-16 17:55:23 -05:00
parent 0b250cd7d3
commit 47db415506
15 changed files with 1097 additions and 1312 deletions

152
TMEX.cs
View File

@@ -3,132 +3,120 @@ using System.Runtime.InteropServices;
namespace OneWireAPI namespace OneWireAPI
{ {
public class TMEX public class TMEX
{ {
#region TMEX function enumerations // Size of the global state buffer
public enum StateBufferSize
{
NoEpromWriting = 5120,
EpromWriting = 15360
}
// Size of the global state buffer // Type of operation for the TMOneWireLevel function
public enum TMStateBufferSize public enum LevelOperation : short
{ {
NoEPROMWriting = 5120, Write = 0,
EPROMWriting = 15360 Read = 1
} }
// Type of operation for the TMOneWireLevel function // TMOneWireLevel operation mode
public enum TMOneWireLevelOperation : short public enum LevelMode : short
{ {
Write = 0, Normal = 0x0,
Read = 1 StrongPullup = 0x1,
} Break = 0x2,
ProgramVoltage = 0x3
}
// TMOneWireLevel operation mode // When the mode from the TMOneWireLevel is to activate
public enum TMOneWireLevelMode : short public enum LevelPrime : short
{ {
Normal = 0x0, Immediate = 0,
StrongPullup = 0x1, AfterNextBit = 1,
Break = 0x2, AfterNextByte = 2
ProgramVoltage = 0x3 }
}
// When the mode from the TMOneWireLevel is to activate // Type of CRC to be calculated
public enum TMOneWireLevelPrime : short public enum CrcType : short
{ {
Immediate = 0, EightBit = 0,
AfterNextBit = 1, SixteenBit = 1
AfterNextByte = 2 }
}
// Type of CRC to be calculated [StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)]
public enum TMCRCType : short public struct FileEntry
{ {
EightBit = 0, [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
SixteenBit = 1 public byte[] Name; /* four-character file name */
} public byte Extension; /* extension number, range 0 - 99, 127 */
public byte StartPage; /* page number where file starts */
#endregion public byte PageCount; /* number of pages occupied by file */
public byte Attributes; /* file/directory attribute */
#region TMEX function structures [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] Bitmap; /* current bitmap of the device */
[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);
[DllImport("IBFS64.DLL")] [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")] [DllImport("IBFS64.DLL")]
public static extern short TMEndSession(int iSession); public static extern int TMExtendedStartSession(short portNumber, short portType, IntPtr enhancedOptions);
[DllImport("IBFS64.DLL")] [DllImport("IBFS64.DLL")]
public static extern short TMReadDefaultPort(out short nPortNumber, out short nPortType); public static extern short TMEndSession(int session);
[DllImport("IBFS64.DLL")] [DllImport("IBFS64.DLL")]
public static extern short TMSetup(int iSession); public static extern short TMReadDefaultPort(out short portNumber, out short portType);
[DllImport("IBFS64.DLL")] [DllImport("IBFS64.DLL")]
public static extern short TMClose(int iSession); public static extern short TMSetup(int session);
[DllImport("IBFS64.DLL")] [DllImport("IBFS64.DLL")]
public static extern short TMRom(int iSession, byte[] bStateBuffer, short[] nROM); public static extern short TMClose(int session);
[DllImport("IBFS64.DLL")] [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")] [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")] [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")] [DllImport("IBFS64.DLL")]
public static extern short TMTouchByte(int iSession, short nOutput); public static extern short TMTouchBit(int session, short output);
[DllImport("IBFS64.DLL")] [DllImport("IBFS64.DLL")]
public static extern short TMTouchReset(int iSession); public static extern short TMTouchByte(int session, short output);
[DllImport("IBFS64.DLL")] [DllImport("IBFS64.DLL")]
public static extern short TMBlockStream(int iSession, byte[] aData, short nByteCount); public static extern short TMTouchReset(int session);
[DllImport("IBFS64.DLL")] [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")] [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")] [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")] [DllImport("IBFS64.DLL")]
public static extern short TMNext(int iSession, byte[] bStateBuffer); public static extern short TMFirst(int session, byte[] stateBuffer);
[DllImport("IBFS64.DLL")] [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")] [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")] [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")] [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);
}
} }

View File

@@ -1,165 +1,150 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owAdapter public class owAdapter
{ {
#region Member variables private static owSession _session;
private static owIdentifier _lastId;
private static owSession m_oSession; // The current session public static void Initialize(owSession session)
private static owIdentifier m_oLastID; // Last ID selected {
// 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) // Copy the ID as the last selected ID
{ _lastId = id;
// Store the session we are dealing with
m_oSession = Session;
}
public static void Select(owIdentifier ID) // Access the device
{ Access();
// Set the ID of the device we want to talk to }
short nResult = TMEX.TMRom(m_oSession.SessionHandle, m_oSession.StateBuffer, ID.RawID);
// Check the result public static void Access()
if (nResult != 1) {
{ // Attempt to access the device
// Throw a ROM exception var result = TMEX.TMAccess(_session.SessionHandle, _session.StateBuffer);
throw new owException(owException.owExceptionFunction.Select, ID, nResult);
}
// Copy the ID as the last selected ID // Check to see if we could access the device
m_oLastID = ID; if (result != 1)
{
// Throw an access exception
throw new owException(owException.ExceptionFunction.Access, _lastId, result);
}
}
// Access the device public static short SendBlock(byte[] data, short byteCount)
Access(); {
} // Send the block and return the result
var result = TMEX.TMBlockStream(_session.SessionHandle, data, byteCount);
public static void Access() // Check to see if the bytes sent matches the value returned
{ if (result != byteCount)
// Attempt to access the device {
short nResult = TMEX.TMAccess(m_oSession.SessionHandle, m_oSession.StateBuffer); // Throw an access exception
throw new owException(owException.ExceptionFunction.SendBlock, _lastId, result);
}
// Check to see if we could access the device // Return the result
if (nResult != 1) return result;
{ }
// Throw an access exception
throw new owException(owException.owExceptionFunction.Access, m_oLastID, nResult);
}
}
public static short SendBlock(byte[] Data, short ByteCount) public static short SendBlock(byte[] data, short byteCount, bool reset)
{ {
// Send the block and return the result // Send the block and return the result
short nResult = TMEX.TMBlockStream(m_oSession.SessionHandle, Data, ByteCount); 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 // Check to see if the bytes sent matches the value returned
if (nResult != ByteCount) if (result != byteCount)
{ {
// Throw an access exception // Throw an access exception
throw new owException(owException.owExceptionFunction.SendBlock, m_oLastID, nResult); throw new owException(owException.ExceptionFunction.SendBlock, _lastId, result);
} }
// Return the result // Return the result
return nResult; return result;
} }
public static short SendBlock(byte[] Data, short ByteCount, bool Reset) public static short ReadBit()
{ {
short nResult; // Send the byte and get back what was sent
var result = TMEX.TMTouchBit(_session.SessionHandle, 0xFF);
// Send the block and return the result // Return the result
if (Reset) return result;
nResult = TMEX.TMBlockStream(m_oSession.SessionHandle, Data, ByteCount); }
else
nResult = TMEX.TMBlockIO(m_oSession.SessionHandle, Data, ByteCount);
// Check to see if the bytes sent matches the value returned public static short SendBit(short output)
if (nResult != ByteCount) {
{ // Send the byte and get back what was sent
// Throw an access exception var result = TMEX.TMTouchBit(_session.SessionHandle, output);
throw new owException(owException.owExceptionFunction.SendBlock, m_oLastID, nResult);
}
// Return the result // Check that the value was sent correctly
return nResult; if (result != output)
} {
// Throw an exception
throw new owException(owException.ExceptionFunction.SendBit, _lastId);
}
public static short ReadBit() // Return the result
{ return result;
// Send the byte and get back what was sent }
short nResult = TMEX.TMTouchBit(m_oSession.SessionHandle, 0xFF);
// Return the result public static short ReadByte()
return nResult; {
} // Send the byte and get back what was sent
var result = TMEX.TMTouchByte(_session.SessionHandle, 0xFF);
public static short SendBit(short Output) // Return the result
{ return result;
// Send the byte and get back what was sent }
short nResult = TMEX.TMTouchBit(m_oSession.SessionHandle, Output);
// Check that the value was sent correctly public static short Reset()
if (nResult != Output) {
{ // Reset all devices
// Throw an exception return TMEX.TMTouchReset(_session.SessionHandle);
throw new owException(owException.owExceptionFunction.SendBit, m_oLastID); }
}
// Return the result public static short SendByte(short output)
return nResult; {
} // Send the byte and get back what was sent
var result = TMEX.TMTouchByte(_session.SessionHandle, output);
public static short ReadByte() // Check that the value was sent correctly
{ if (result != output)
// Send the byte and get back what was sent {
short nResult = TMEX.TMTouchByte(m_oSession.SessionHandle, 0xFF); // Throw an exception
throw new owException(owException.ExceptionFunction.SendByte, _lastId);
}
// Return the result // Return the result
return nResult; return result;
} }
public static short Reset() public static short SetLevel(TMEX.LevelOperation nOperation, TMEX.LevelMode nLevelMode, TMEX.LevelPrime nPrimed)
{ {
// Reset all devices // Set the level
return TMEX.TMTouchReset(m_oSession.SessionHandle); var result = TMEX.TMOneWireLevel(_session.SessionHandle, TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate);
}
public static short SendByte(short Output) // Check the result
{ if (result < 0)
// Send the byte and get back what was sent {
short nResult = TMEX.TMTouchByte(m_oSession.SessionHandle, Output); // Throw an exception
throw new owException(owException.ExceptionFunction.SetLevel, result);
}
// Check that the value was sent correctly // Return the result
if (nResult != Output) return result;
{ }
// 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
}
} }

View File

@@ -1,16 +1,8 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
internal class owCRC16 internal class owCRC16
{ {
#region CRC lookup table private static readonly short[] OddParity = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
private static short[] m_aOddParity = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
#endregion
#region Methods
public static int Calculate(byte[] nData, int iStart, int iEnd) public static int Calculate(byte[] nData, int iStart, int iEnd)
{ {
@@ -19,7 +11,7 @@ namespace OneWireAPI
public static int Calculate(byte nData, int iInitialValue) public static int Calculate(byte nData, int iInitialValue)
{ {
byte[] aData = new byte[1]; var aData = new byte[1];
aData[0] = nData; aData[0] = nData;
@@ -28,34 +20,32 @@ namespace OneWireAPI
public static int Calculate(byte[] nData, int iStart, int iEnd, int iInitialValue) public static int Calculate(byte[] nData, int iStart, int iEnd, int iInitialValue)
{ {
int iIndex; // Loop index int index; // Loop index
int iCurrentCRC = iInitialValue; // Current CRC accumulator var currentCrc = iInitialValue; // Current CRC accumulator
// Loop over all bytes in the input array // 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 // Get the current element of data
int iBuffer = nData[iIndex]; int iBuffer = nData[index];
// Calculate the current CRC for this position // 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) if ((OddParity[iBuffer & 0xF] ^ OddParity[iBuffer >> 4]) != 0)
iCurrentCRC ^= 0xC001; currentCrc ^= 0xC001;
iBuffer <<= 6; iBuffer <<= 6;
iCurrentCRC ^= iBuffer; currentCrc ^= iBuffer;
iBuffer <<= 1; iBuffer <<= 1;
iCurrentCRC ^= iBuffer; currentCrc ^= iBuffer;
} }
// Return the final CRC value // Return the final CRC value
return iCurrentCRC; return currentCrc;
} }
#endregion
} }
} }

104
owCRC8.cs
View File

@@ -1,76 +1,52 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
internal class owCRC8 internal class owCRC8
{ {
#region Member variables 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() for (var inner = 0; inner < 8; inner++)
{ {
// Initialize the CRC lookup table if (((accumulator ^ crc) & 0x01) == 0x01)
InitializeCRCTable(); crc = ((crc ^ 0x18) >> 1) | 0x80;
} else
crc = crc >> 1;
#endregion accumulator = accumulator >> 1;
}
#region Private methods _dataTable[outer] = (byte) crc;
}
}
private static void InitializeCRCTable() public static short Calculate(byte[] data, int start, int end)
{ {
int iAccumulator; // Accumulator value var currentCrc = (short) 0; // Current CRC accumulator
int iCRC; // CRC value
int iOuter; // Outer loop control
int iInner; // Inner loop control
// Initialize the size of the lookup table // Loop over all bytes in the input array
m_aDataTable = new byte[256]; 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++) // Return the final CRC value
{ return currentCrc;
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
}
} }

View File

@@ -1,41 +1,27 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDevice public class owDevice
{ {
#region Member variables protected owSession Session;
protected owIdentifier DeviceId;
protected owSession _session; // The current session public owDevice(owSession session, short[] rawId)
protected owIdentifier _deviceID; // The ID of this device
#endregion
#region Constructor
public owDevice(owSession session, short[] rawID)
{ {
// Store the session // Store the session
_session = session; Session = session;
// Create a new identifier and give it the ID supplied // Create a new identifier and give it the ID supplied
_deviceID = new owIdentifier(rawID); DeviceId = new owIdentifier(rawId);
} }
#endregion public owIdentifier Id
#region Properties
public owIdentifier ID
{ {
get { return _deviceID; } get { return DeviceId; }
} }
public int Family public int Family
{ {
get { return _deviceID.Family; } get { return DeviceId.Family; }
} }
#endregion
} }
} }

View File

@@ -1,102 +1,90 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDeviceFamily10 : owDevice public class owDeviceFamily10 : owDevice
{ {
#region Constructor public owDeviceFamily10(owSession session, short[] id)
: base(session, id)
{
// Just call the base constructor
}
public owDeviceFamily10(owSession Session, short[] ID) : base(Session, ID) public double GetTemperature()
{ {
// Just call the base constructor // 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() // Re-throw the exception
{ throw;
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
// Select and access the ID of the device we want to talk to // Sleep while the data is transfered
owAdapter.Select(_deviceID); System.Threading.Thread.Sleep(1000);
// Setup for for power delivery after the next byte // Stop the strong pullup
nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.StrongPullup, TMEX.TMOneWireLevelPrime.AfterNextByte); owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate);
try // Access the device we want to talk to
{ owAdapter.Access();
// 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);
// Re-throw the exception // Data buffer to send over the network
throw; var data = new byte[30];
}
// Sleep while the data is transfered // How many bytes of data to send
System.Threading.Thread.Sleep(1000); short dataCount = 0;
// Stop the strong pullup // Set the command to get the temperature from the scatchpad
nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); data[dataCount++] = 0xBE;
// Access the device we want to talk to // Setup the rest of the bytes that we want
owAdapter.Access(); for (var i = 0; i < 9; i++)
data[dataCount++] = 0xFF;
// Set the command to get the temperature from the scatchpad // Send the data block and get data back
aData[nDataCount++] = 0xBE; owAdapter.SendBlock(data, dataCount);
// Setup the rest of the bytes that we want // Calculate the CRC of the first eight bytes of data
for (int i = 0; i < 9; i++) var crc = owCRC8.Calculate(data, 1, 8);
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 // Check to see if our CRC matches the CRC supplied
nCRC = owCRC8.Calculate(aData, 1, 8); 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 // Get the LSB of the temperature data and divide it by two
if (nCRC != aData[9]) var temperatureLsb = data[1] / 2;
{
// Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
// Get the LSB of the temperature data and divide it by two // If the data is negative then flip the bits
iTemperatureLSB = aData[1] / 2; if ((data[2] & 0x01) == 0x01) temperatureLsb |= -128;
// If the data is negative then flip the bits // Convert the temperature into a double
if ((aData[2] & 0x01) == 0x01) iTemperatureLSB |= -128; var temperature = (double) temperatureLsb;
// Convert the temperature into a double // Get the number of counts remaining
dTemperature = (double) iTemperatureLSB; double countRemaining = data[7];
// Get the number of counts remaining // Get the number of counts per degree C
dCountRemaining = aData[7]; double countPerDegreeC = data[8];
// Get the number of counts per degree C // Use the "counts remaining" data to calculate the temperaure to greater accuracy
dCountPerDegreeC = aData[8]; temperature = temperature - 0.25F + (countPerDegreeC - countRemaining) / countPerDegreeC;
// Use the "counts remaining" data to calculate the temperaure to greater accuracy // Return the temperature
dTemperature = dTemperature - 0.25F + (dCountPerDegreeC - dCountRemaining) / dCountPerDegreeC; return temperature;
}
// Return the temperature }
return dTemperature;
}
#endregion
}
} }

View File

@@ -1,199 +1,184 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDeviceFamily12 : owDevice public class owDeviceFamily12 : owDevice
{ {
#region Constants 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 public owDeviceFamily12(owSession session, short[] id)
private const byte WRITE_STATUS_COMMAND = 0x55; // Command value to write the status : base(session, id)
private const byte READ_STATUS_COMMAND = 0xAA; // Command value to read the status {
// Just call the base constructor
}
#endregion public bool IsPowered(byte[] state)
{
#region Constructor return ((state[0] & 0x80) == 0x80);
}
public owDeviceFamily12(owSession Session, short[] ID) : base(Session, ID) public bool GetLevel(int channel, byte[] state)
{ {
// Just call the base constructor 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[1] & 0x40) != 0x40);
{ }
return ((State[0] & 0x80) == 0x80);
}
public bool GetLevel(int Channel, byte[] State) public void SetLatchState(int channel, bool latchState, byte[] state)
{ {
if (Channel == 0) if (channel == 0)
return ((State[0] & 0x04) == 0x04); {
else state[1] &= 0xDF;
return ((State[0] & 0x08) == 0x08);
}
public bool GetLatchState(int Channel, byte[] State) if (!latchState)
{ state[1] = (byte) (state[1] | 0x20);
if (Channel == 0) }
{ else
return ((State[1] & 0x20) != 0x20); {
} state[1] &= 0xBF;
else
{
return ((State[1] & 0x40) != 0x40);
}
}
public void SetLatchState(int Channel, bool LatchState, byte[] State) if (!latchState)
{ state[1] = (byte) (state[1] | 0x40);
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);
}
}
public byte[] ReadDevice() public byte[] ReadDevice()
{ {
byte[] State = new byte[2]; // Select and access the ID of the device we want to talk to
byte[] aData = new byte[30]; // Data buffer to send over the network owAdapter.Select(DeviceId);
short nDataCount = 0; // How many bytes of data to send
int iCRCResult; // Result of the CRC calculation
int iMatchCRC; // CRC retrieved from the device
// Select and access the ID of the device we want to talk to // Data buffer to send over the network
owAdapter.Select(_deviceID); var data = new byte[30];
// Set the commmand to execute // How many bytes of data to send
aData[nDataCount++] = CHANNEL_ACCESS_COMMAND; short dataCount = 0;
// Set the data // Set the commmand to execute
aData[nDataCount++] = 0x55; data[dataCount++] = ChannelAccessCommand;
aData[nDataCount++] = 0xFF;
// Read the info, dummy data and CRC16 // Set the data
for (int i = 3; i < 7; i++) data[dataCount++] = 0x55;
aData[nDataCount++] = 0xFF; data[dataCount++] = 0xFF;
// Send the data // Read the info, dummy data and CRC16
owAdapter.SendBlock(aData, nDataCount); for (var i = 3; i < 7; i++)
data[dataCount++] = 0xFF;
// Calculate the CRC // Send the data
iCRCResult = owCRC16.Calculate(aData, 0, 4); owAdapter.SendBlock(data, dataCount);
// Assemble the CRC provided by the device // Calculate the CRC
iMatchCRC = aData[6] << 8; var crcResult = owCRC16.Calculate(data, 0, 4);
iMatchCRC |= aData[5];
iMatchCRC ^= 0xFFFF;
// Make sure the CRC values match // Assemble the CRC provided by the device
if (iCRCResult != iMatchCRC) var matchCrc = data[6] << 8;
{ matchCrc |= data[5];
// Throw a CRC exception matchCrc ^= 0xFFFF;
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
// Store the state data // Make sure the CRC values match
State[0] = aData[3]; if (crcResult != matchCrc)
{
// Throw a CRC exception
throw new owException(owException.ExceptionFunction.Crc, DeviceId);
}
// Reset the data count var state = new byte[2];
nDataCount = 0;
// Set the command // Store the state data
aData[nDataCount++] = READ_STATUS_COMMAND; state[0] = data[3];
// Set the address to read // Reset the data count
aData[nDataCount++] = 7; dataCount = 0;
aData[nDataCount++] = 0;
// Add data for the CRC // Set the command
for (int i = 3; i < 6; i++) data[dataCount++] = ReadStatusCommand;
aData[nDataCount++] = 0xFF;
// Select and access the ID of the device we want to talk to // Set the address to read
owAdapter.Select(_deviceID); data[dataCount++] = 7;
data[dataCount++] = 0;
// Send the data // Add data for the CRC
owAdapter.SendBlock(aData, nDataCount); for (var i = 3; i < 6; i++)
data[dataCount++] = 0xFF;
// Calculate the CRC // Select and access the ID of the device we want to talk to
iCRCResult = owCRC16.Calculate(aData, 0, 3); owAdapter.Select(DeviceId);
// Assemble the CRC provided by the device // Send the data
iMatchCRC = aData[5] << 8; owAdapter.SendBlock(data, dataCount);
iMatchCRC |= aData[4];
iMatchCRC ^= 0xFFFF;
// Make sure the CRC values match // Calculate the CRC
if (iCRCResult != iMatchCRC) crcResult = owCRC16.Calculate(data, 0, 3);
{
// Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
// Store the state data // Assemble the CRC provided by the device
State[1] = aData[3]; 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) // Store the state data
{ state[1] = data[3];
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
// Select and access the ID of the device we want to talk to return state;
owAdapter.Select(_deviceID); }
// Set the commmand to execute public void WriteDevice(byte[] state)
aData[nDataCount++] = WRITE_STATUS_COMMAND; {
// Select and access the ID of the device we want to talk to
owAdapter.Select(DeviceId);
// Set the address // Data buffer to send over the network
aData[nDataCount++] = 0x07; var data = new byte[30];
aData[nDataCount++] = 0x00;
// Add the state // How many bytes of data to send
aData[nDataCount++] = State[1]; short dataCount = 0;
// Add bytes for the CRC result // Set the commmand to execute
aData[nDataCount++] = 0xFF; data[dataCount++] = WriteStatusCommand;
aData[nDataCount++] = 0xFF;
// Send the data // Set the address
nResult = owAdapter.SendBlock(aData, nDataCount); data[dataCount++] = 0x07;
data[dataCount++] = 0x00;
// Calculate the CRC // Add the state
iCRCResult = owCRC16.Calculate(aData, 0, 3); data[dataCount++] = state[1];
// Assemble the CRC provided by the device // Add bytes for the CRC result
iMatchCRC = aData[5] << 8; data[dataCount++] = 0xFF;
iMatchCRC |= aData[4]; data[dataCount++] = 0xFF;
iMatchCRC ^= 0xFFFF;
// Make sure the CRC values match // Send the data
if (iCRCResult != iMatchCRC) owAdapter.SendBlock(data, dataCount);
{
// Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
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);
}
}
}
} }

View File

@@ -1,76 +1,67 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDeviceFamily1D : owDevice public class owDeviceFamily1D : owDevice
{ {
#region Constructor public owDeviceFamily1D(owSession session, short[] id)
: base(session, id)
{
// Just call the base constructor
}
public owDeviceFamily1D(owSession Session, short[] ID) : base(Session, ID) public uint GetCounter(int counterPage)
{ {
// Just call the base constructor // 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) // Set the "read memory and counter" command into the data array
{ data[dataCount++] = 0xA5;
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
// Select and access the ID of the device we want to talk to // Calculate the position of the last byte in the page
owAdapter.Select(_deviceID); var lastByte = (counterPage << 5) + 31;
// Set the "read memory and counter" command into the data array // Copy the lower byte of the last byte into the data array
aData[nDataCount++] = 0xA5; data[dataCount++] = (byte) (lastByte & 0xFF);
// Calculate the position of the last byte in the page // Copy the upper byte of the last byte into the data array
iLastByte = (CounterPage << 5) + 31; data[dataCount++] = (byte) (lastByte >> 8);
// Copy the lower byte of the last byte into the data array // Add byte for the data byate, counter, zero bits, and CRC16 result
aData[nDataCount++] = (byte) (iLastByte & 0xFF); for (var i = 0; i < 11; i++) data[dataCount++] = 0xFF;
// Copy the upper byte of the last byte into the data array // Send the block of data to the device
aData[nDataCount++] = (byte) (iLastByte >> 8); owAdapter.SendBlock(data, dataCount);
// Add byte for the data byate, counter, zero bits, and CRC16 result // Calculate the CRC based on the data
for (int i = 0; i < 11; i++) aData[nDataCount++] = 0xFF; var crcResult = owCRC16.Calculate(data, 0, 11);
// Send the block of data to the device // Assemble the CRC provided by the device
nResult = owAdapter.SendBlock(aData, nDataCount); var matchCrc = data[13] << 8;
matchCrc |= data[12];
matchCrc ^= 0xFFFF;
// Calculate the CRC based on the data // Make sure the CRC values match
iCRCResult = owCRC16.Calculate(aData, 0, 11); if (crcResult != matchCrc)
{
// Throw a CRC exception
throw new owException(owException.ExceptionFunction.Crc, DeviceId);
}
// Assemble the CRC provided by the device uint counter = 0;
iMatchCRC = aData[13] << 8;
iMatchCRC |= aData[12];
iMatchCRC ^= 0xFFFF;
// Make sure the CRC values match // Assemble the counter data from the bytes retrieved
if (iCRCResult != iMatchCRC) for (var i = dataCount - 7; i >= dataCount - 10; i--)
{ {
// Throw a CRC exception counter <<= 8;
throw new owException(owException.owExceptionFunction.CRC, _deviceID); counter |= data[i];
} }
// Assemble the counter data from the bytes retrieved return counter;
for (int i = nDataCount - 7; i >= nDataCount - 10; i--) }
{ }
iCounter <<= 8;
iCounter |= aData[i];
}
return iCounter;
}
#endregion
}
} }

View File

@@ -1,258 +1,242 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDeviceFamily20 : owDevice public class owDeviceFamily20 : owDevice
{ {
#region Member variables 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 public void Initialize()
{ {
Range_512 = 0x01, const int startAddress = 0x8; // Starting data page address
Range_256 = 0x00 const int endAddress = 0x11; // Ending data page address
}
public enum owDeviceFamily20Resolution : byte // Setup the control page
{ for (var index = 0; index < 8; index += 2)
EightBits = 0x08, {
SixteenBits = 0x00 _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() // Select and access the ID of the device we want to talk to
{ owAdapter.Select(DeviceId);
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
// Setup the control page // Write to the data pages specified
for (iIndex = 0; iIndex < 8; iIndex += 2) for (var index = startAddress; index <= endAddress; index++)
{ {
m_aControl[iIndex] = (byte) owDeviceFamily20Resolution.EightBits; // Copy the control data into our output buffer
m_aControl[iIndex + 1] = (byte) owDeviceFamily20Range.Range_512; data[dataCount++] = _control[index - startAddress];
}
// Clear the alarm page // Add two bytes for the CRC results
for (iIndex = 8; iIndex < 16; iIndex++) data[dataCount++] = 0xFF;
{ data[dataCount++] = 0xFF;
m_aControl[iIndex] = 0;
}
// Set the command into the data array // Add a byte for the control byte echo
aData[nDataCount++] = 0x55; data[dataCount++] = 0xFF;
// Set the starting address of the data to write // Send the block
aData[nDataCount++] = (byte) (iStartAddress & 0xFF); owAdapter.SendBlock(data, dataCount);
aData[nDataCount++] = (byte) ((iStartAddress >> 8) & 0xFF);
// Select and access the ID of the device we want to talk to // If the check byte doesn't match then throw an exception
owAdapter.Select(_deviceID); if (data[dataCount - 1] != _control[index - startAddress])
{
// Throw an exception
throw new owException(owException.ExceptionFunction.SendBlock, DeviceId);
}
// Write to the data pages specified int calculatedCrc; // CRC we calculated from sent data
for (iIndex = iStartAddress; iIndex <= iEndAddress; iIndex++) int sentCrc; // CRC retrieved from the device
{
// Copy the control data into our output buffer
aData[nDataCount++] = m_aControl[iIndex - iStartAddress];
// Add two bytes for the CRC results // Calculate the CRC values
aData[nDataCount++] = 0xFF; if (index == startAddress)
aData[nDataCount++] = 0xFF; {
// Calculate the CRC16 of the data sent
calculatedCrc = owCRC16.Calculate(data, 0, 3);
// Add a byte for the control byte echo // Reconstruct the CRC sent by the device
aData[nDataCount++] = 0xFF; sentCrc = data[dataCount - 2] << 8;
sentCrc |= data[dataCount - 3];
// Send the block sentCrc ^= 0xFFFF;
nResult = owAdapter.SendBlock(aData, nDataCount); }
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 // Reconstruct the CRC sent by the device
if (aData[nDataCount - 1] != m_aControl[iIndex - iStartAddress]) sentCrc = data[dataCount - 2] << 8;
{ sentCrc |= data[dataCount - 3];
// Throw an exception sentCrc ^= 0xFFFF;
throw new owException(owException.owExceptionFunction.SendBlock, _deviceID); }
}
// Calculate the CRC values // If the CRC doesn't match then throw an exception
if (iIndex == iStartAddress) if (calculatedCrc != sentCrc)
{ {
// Calculate the CRC16 of the data sent // Throw a CRC exception
iCalculatedCRC = owCRC16.Calculate(aData, 0, 3); throw new owException(owException.ExceptionFunction.Crc, DeviceId);
}
// Reconstruct the CRC sent by the device // Reset the byte count
iSentCRC = aData[nDataCount - 2] << 8; dataCount = 0;
iSentCRC |= aData[nDataCount - 3]; }
iSentCRC ^= 0xFFFF; }
}
else
{
// Calculate the CRC16 of the data sent
iCalculatedCRC = owCRC16.Calculate(m_aControl[iIndex - iStartAddress], iIndex);
// Reconstruct the CRC sent by the device public double[] GetVoltages()
iSentCRC = aData[nDataCount - 2] << 8; {
iSentCRC |= aData[nDataCount - 3]; // Select and access the ID of the device we want to talk to
iSentCRC ^= 0xFFFF; owAdapter.Select(DeviceId);
}
// If the CRC doesn't match then throw an exception // Data buffer to send over the network
if (iCalculatedCRC != iSentCRC) var data = new byte[30];
{
// Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
// Reset the byte count // How many bytes of data to send
nDataCount = 0; short dataCount = 0;
}
}
public double[] GetVoltages() // Set the convert command into the transmit buffer
{ data[dataCount++] = 0x3C;
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
// Select and access the ID of the device we want to talk to // Set the input mask to get all channels
owAdapter.Select(_deviceID); data[dataCount++] = 0x0F;
// Set the convert command into the transmit buffer // Set the read-out control to leave things as they are
aData[nDataCount++] = 0x3C; data[dataCount++] = 0x00;
// Set the input mask to get all channels // Add two bytes for the CRC results
aData[nDataCount++] = 0x0F; data[dataCount++] = 0xFF;
data[dataCount++] = 0xFF;
// Set the read-out control to leave things as they are // Send the data block
aData[nDataCount++] = 0x00; owAdapter.SendBlock(data, dataCount);
// Add two bytes for the CRC results // Calculate the CRC based on the transmit buffer
aData[nDataCount++] = 0xFF; var calculatedCrc = owCRC16.Calculate(data, 0, 2);
aData[nDataCount++] = 0xFF;
// Send the data block // Reconstruct the CRC sent by the device
owAdapter.SendBlock(aData, nDataCount); var sentCrc = data[4] << 8;
sentCrc |= data[3];
sentCrc ^= 0xFFFF;
// Calculate the CRC based on the transmit buffer // If the CRC doesn't match then throw an exception
iCalculatedCRC = owCRC16.Calculate(aData, 0, 2); if (calculatedCrc != sentCrc)
{
// Throw a CRC exception
throw new owException(owException.ExceptionFunction.Crc, DeviceId);
}
// Reconstruct the CRC sent by the device // Setup for for power delivery after the next byte
iSentCRC = aData[4] << 8; owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.StrongPullup, TMEX.LevelPrime.AfterNextByte);
iSentCRC |= aData[3];
iSentCRC ^= 0xFFFF;
// If the CRC doesn't match then throw an exception var nTransmitByte = (short) ((dataCount - 1) & 0x1F);
if (iCalculatedCRC != iSentCRC)
{
// Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
// Setup for for power delivery after the next byte try
nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.StrongPullup, TMEX.TMOneWireLevelPrime.AfterNextByte); {
// 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 // Sleep while the data is transfered
{ System.Threading.Thread.Sleep(6);
// 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);
// Re-throw the exception // Stop the strong pullup
throw; owAdapter.SetLevel(TMEX.LevelOperation.Write, TMEX.LevelMode.Normal, TMEX.LevelPrime.Immediate);
}
// Sleep while the data is transfered // Read data to see if the conversion is over
System.Threading.Thread.Sleep(6); owAdapter.ReadByte();
// Stop the strong pullup // Select and access the ID of the device we want to talk to
nResult = owAdapter.SetLevel(TMEX.TMOneWireLevelOperation.Write, TMEX.TMOneWireLevelMode.Normal, TMEX.TMOneWireLevelPrime.Immediate); owAdapter.Select(DeviceId);
// Read data to see if the conversion is over // Reinitialize the data count
nCheckByte = owAdapter.ReadByte(); dataCount = 0;
// Select and access the ID of the device we want to talk to // Set the read command into the transmit buffer
owAdapter.Select(_deviceID); data[dataCount++] = 0xAA;
// Reinitialize the data count // Set the address to get the conversion results
nDataCount = 0; data[dataCount++] = 0x00;
data[dataCount++] = 0x00;
// Set the read command into the transmit buffer // Add 10 bytes to be read - 8 for the data and 2 for the CRC
aData[nDataCount++] = 0xAA; for (var index = 0; index < 10; index++)
data[dataCount++] = 0xFF;
// Set the address to get the conversion results // Send the block to the device
aData[nDataCount++] = 0x00; owAdapter.SendBlock(data, dataCount);
aData[nDataCount++] = 0x00;
// Add 10 bytes to be read - 8 for the data and 2 for the CRC // Calculate the CRC of the transmitted data
for (iIndex = 0; iIndex < 10; iIndex++) calculatedCrc = owCRC16.Calculate(data, 0, 10);
aData[nDataCount++] = 0xFF;
// Send the block to the device // Reconstruct the CRC sent by the device
nResult = owAdapter.SendBlock(aData, nDataCount); sentCrc = data[dataCount - 1] << 8;
sentCrc |= data[dataCount - 2];
sentCrc ^= 0xFFFF;
// Calculate the CRC of the transmitted data // If the CRC doesn't match then throw an exception
iCalculatedCRC = owCRC16.Calculate(aData, 0, 10); if (calculatedCrc != sentCrc)
{
// Throw a CRC exception
throw new owException(owException.ExceptionFunction.Crc, DeviceId);
}
// Reconstruct the CRC sent by the device // Voltage values to return
iSentCRC = aData[nDataCount - 1] << 8; var voltages = new double[4];
iSentCRC |= aData[nDataCount - 2];
iSentCRC ^= 0xFFFF;
// If the CRC doesn't match then throw an exception // Convert the data into a double
if (iCalculatedCRC != iSentCRC) for (var index = 3; index < 11; index += 2)
{ {
// Throw a CRC exception // Reconstruct the two bytes into the 16-bit values
throw new owException(owException.owExceptionFunction.CRC, _deviceID); var iVoltageReadout = ((data[index + 1] << 8) | data[index]) & 0x0000FFFF;
}
// Convert the data into a double // Figure out the percentage of the top voltage is present
for (iIndex = 3; iIndex < 11; iIndex += 2) voltages[(index - 3) / 2] = iVoltageReadout / 65535.0;
{
// 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 // Apply the percentage to the maximum voltage range
dVoltages[(iIndex - 3) / 2] = iVoltageReadout / 65535.0; voltages[(index - 3) / 2] *= ((_control[(index - 3) + 1] & 0x01) == 0x01 ? 5.12 : 2.56);
}
// Apply the percentage to the maximum voltage range return voltages;
dVoltages[(iIndex - 3) / 2] *= ((m_aControl[(iIndex - 3) + 1] & 0x01) == 0x01 ? 5.12 : 2.56); }
} }
return dVoltages;
}
#endregion
}
} }

View File

@@ -1,277 +1,262 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDeviceFamily26 : owDevice public class owDeviceFamily26 : owDevice
{ {
#region Constructor public owDeviceFamily26(owSession session, short[] id)
: base(session, id)
{
// Just call the base constructor
}
public owDeviceFamily26(owSession Session, short[] ID) : base(Session, ID) public enum VoltageType : short
{ {
// Just call the base constructor 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 // Data buffer to send over the network
{ var data = new byte[30];
Supply,
Output
}
private double GetVoltage(VoltageType Type) // How many bytes of data to send
{ short dataCount = 0;
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;
// Select and access the ID of the device we want to talk to // Set the command to recall the status/configuration page to the scratchpad
owAdapter.Select(_deviceID); data[dataCount++] = 0xB8;
// Set the command to recall the status/configuration page to the scratchpad
aData[nDataCount++] = 0xB8;
// Set the page number to recall // Set the page number to recall
aData[nDataCount++] = 0x00; data[dataCount++] = 0x00;
// Send the data block // Send the data block
nResult = owAdapter.SendBlock(aData, nDataCount); owAdapter.SendBlock(data, dataCount);
// Clear the data count // Clear the data count
nDataCount = 0; dataCount = 0;
// Access the device we want to talk to // Access the device we want to talk to
owAdapter.Access(); owAdapter.Access();
// Set the command to read the scratchpad // Set the command to read the scratchpad
aData[nDataCount++] = 0xBE; data[dataCount++] = 0xBE;
// Set the page number to read // Set the page number to read
aData[nDataCount++] = 0x00; data[dataCount++] = 0x00;
// Add 9 bytes to be read - 8 for the data and 1 for the CRC // Add 9 bytes to be read - 8 for the data and 1 for the CRC
for (iIndex = 0; iIndex < 9; iIndex++) for (var index = 0; index < 9; index++)
aData[nDataCount++] = 0xFF; data[dataCount++] = 0xFF;
// Send the data block // Send the data block
nResult = owAdapter.SendBlock(aData, nDataCount); owAdapter.SendBlock(data, dataCount);
// Calculate the CRC of the scratchpad data // Calculate the CRC of the scratchpad data
nCRC = owCRC8.Calculate(aData, 2, 9); var crc = owCRC8.Calculate(data, 2, 9);
// If the CRC doesn't match then throw an exception // If the CRC doesn't match then throw an exception
if (nCRC != aData[10]) if (crc != data[10])
{ {
// Throw a CRC exception // Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID); throw new owException(owException.ExceptionFunction.Crc, DeviceId);
} }
// TODO - Check if we really need to change the input selector // TODO - Check if we really need to change the input selector
if (true) if (true)
{ {
// Access the device we want to talk to // Access the device we want to talk to
owAdapter.Access(); owAdapter.Access();
// Reset the data count // Reset the data count
nDataCount = 0; dataCount = 0;
// Set the command to write the scratchpad // Set the command to write the scratchpad
aData[nDataCount++] = 0x4E; data[dataCount++] = 0x4E;
// Set the page number to write // Set the page number to write
aData[nDataCount++] = 0x00; data[dataCount++] = 0x00;
// Set or clear the AD bit based on the type requested // Set or clear the AD bit based on the type requested
if (Type == VoltageType.Supply) if (type == VoltageType.Supply)
aData[nDataCount++] = (byte) (aData[2] | 0x08); data[dataCount++] = (byte) (data[2] | 0x08);
else else
aData[nDataCount++] = (byte) (aData[2] & 0xF7); data[dataCount++] = (byte) (data[2] & 0xF7);
// Move the existing data down in the array // Move the existing data down in the array
for (iIndex = 0; iIndex < 7; iIndex++) for (var index = 0; index < 7; index++)
aData[nDataCount++] = aData[iIndex + 4]; data[dataCount++] = data[index + 4];
// Send the data block // Send the data block
nResult = owAdapter.SendBlock(aData, nDataCount); owAdapter.SendBlock(data, dataCount);
// Reset the data count // Reset the data count
nDataCount = 0; dataCount = 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);
}
// Access the device we want to talk to // Access the device we want to talk to
owAdapter.Access(); owAdapter.Access();
// Send the voltage conversion command // Set the command to copy the scratchpad
owAdapter.SendByte(0xB4); data[dataCount++] = 0x48;
// Loop until conversion is complete // Set the page number to copy to
do data[dataCount++] = 0x00;
{
nBusy = owAdapter.ReadByte();
}
while (nBusy == 0);
// Clear the data count // Send the data block
nDataCount = 0; owAdapter.SendBlock(data, dataCount);
// Set the command to recall the status/configuration page to the scratchpad // Loop until the data copy is complete
aData[nDataCount++] = 0xB8; do
{
busy = owAdapter.ReadByte();
}
while (busy == 0);
}
// Set the page number to recall // Access the device we want to talk to
aData[nDataCount++] = 0x00; owAdapter.Access();
// Access the device we want to talk to // Send the voltage conversion command
owAdapter.Access(); owAdapter.SendByte(0xB4);
// Send the data block // Loop until conversion is complete
nResult = owAdapter.SendBlock(aData, nDataCount); do
{
busy = owAdapter.ReadByte();
}
while (busy == 0);
// Clear the data count // Clear the data count
nDataCount = 0; dataCount = 0;
// Access the device we want to talk to // Set the command to recall the status/configuration page to the scratchpad
owAdapter.Access(); data[dataCount++] = 0xB8;
// Set the command to read the scratchpad // Set the page number to recall
aData[nDataCount++] = 0xBE; data[dataCount++] = 0x00;
// Set the page number to read // Access the device we want to talk to
aData[nDataCount++] = 0x00; owAdapter.Access();
// Add 9 bytes to be read - 8 for the data and 1 for the CRC // Send the data block
for (iIndex = 0; iIndex < 9; iIndex++) owAdapter.SendBlock(data, dataCount);
aData[nDataCount++] = 0xFF;
// Send the data block // Clear the data count
nResult = owAdapter.SendBlock(aData, nDataCount); dataCount = 0;
// Calculate the CRC of the scratchpad data // Access the device we want to talk to
nCRC = owCRC8.Calculate(aData, 2, 9); owAdapter.Access();
// If the CRC doesn't match then throw an exception // Set the command to read the scratchpad
if (nCRC != aData[10]) data[dataCount++] = 0xBE;
{
// 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;
}
public double GetSupplyVoltage() // Set the page number to read
{ data[dataCount++] = 0x00;
return GetVoltage(VoltageType.Supply);
}
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() // Calculate the CRC of the scratchpad data
{ crc = owCRC8.Calculate(data, 2, 9);
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
// Select and access the ID of the device we want to talk to // If the CRC doesn't match then throw an exception
owAdapter.Select(_deviceID); if (crc != data[10])
{
// Throw a CRC exception
throw new owException(owException.ExceptionFunction.Crc, DeviceId);
}
// Send the conversion command byte // Assemble the voltage data
owAdapter.SendByte(0x44); var dVoltage = (double) ((data[6] << 8) | data[5]);
// Sleep while the data is converted return dVoltage / 100;
System.Threading.Thread.Sleep(10); }
// Access the device we want to talk to public double GetSupplyVoltage()
owAdapter.Access(); {
return GetVoltage(VoltageType.Supply);
}
// Set the command to recall the status/configuration page to the scratchpad public double GetOutputVoltage()
aData[nDataCount++] = 0xB8; {
// Set the page number to recall return GetVoltage(VoltageType.Output);
aData[nDataCount++] = 0x00; }
// Send the data block public double GetTemperature()
nResult = owAdapter.SendBlock(aData, nDataCount); {
// Select and access the ID of the device we want to talk to
owAdapter.Select(DeviceId);
// Clear the data count // Send the conversion command byte
nDataCount = 0; owAdapter.SendByte(0x44);
// Access the device we want to talk to // Sleep while the data is converted
owAdapter.Access(); System.Threading.Thread.Sleep(10);
// Set the command to read the scratchpad // Access the device we want to talk to
aData[nDataCount++] = 0xBE; owAdapter.Access();
// Set the page number to read // Data buffer to send over the network
aData[nDataCount++] = 0x00; var data = new byte[30];
// Add 9 bytes to be read - 8 for the data and 1 for the CRC // How many bytes of data to send
for (int iIndex = 0; iIndex < 9; iIndex++) short dataCount = 0;
aData[nDataCount++] = 0xFF;
// Send the data block // Set the command to recall the status/configuration page to the scratchpad
nResult = owAdapter.SendBlock(aData, nDataCount); data[dataCount++] = 0xB8;
// Calculate the CRC of the scratchpad data // Set the page number to recall
nCRC = owCRC8.Calculate(aData, 2, 9); data[dataCount++] = 0x00;
// If the CRC doesn't match then throw an exception // Send the data block
if (nCRC != aData[10]) owAdapter.SendBlock(data, dataCount);
{
// Throw a CRC exception
throw new owException(owException.owExceptionFunction.CRC, _deviceID);
}
// Get the two bytes of temperature data // Clear the data count
iTemperatureLSB = aData[3]; dataCount = 0;
iTemperatureMSB = aData[4];
// Shift the data into the right order // Access the device we want to talk to
iTemperature = ((iTemperatureMSB << 8) | iTemperatureLSB) >> 3; owAdapter.Access();
// Figure out the temperature // Set the command to read the scratchpad
dTemperature = iTemperature * 0.03125F; data[dataCount++] = 0xBE;
// Return the temperature // Set the page number to read
return dTemperature; 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;
}
}
} }

View File

@@ -1,172 +1,172 @@
using System;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owDeviceFamilyFF : owDevice public class owDeviceFamilyFF : owDevice
{ {
#region Member variables private int _width = 20;
private int _height = 4;
private int m_iWidth = 20; public owDeviceFamilyFF(owSession session, short[] id)
private int m_iHeight = 4; : 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) // Set the state of the backlight
{ owAdapter.SendByte((short) (state ? 0x8 : 0x7));
// Just call the base constructor }
}
#endregion public void SetText(string text)
{
#region Methods // Line number
var line = 1;
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
// Replace any CRLF pairs with just a newline // Replace any CRLF pairs with just a newline
Text = Text.Replace("\r\n", "\n"); text = text.Replace("\r\n", "\n");
// Split the input string at any newlines
sLines = Text.Split("\n".ToCharArray(), m_iHeight);
// Loop over each line // Split the input string at any newlines
foreach (string sLine in sLines) var sLines = text.Split("\n".ToCharArray(), _height);
{
// Set the text of this line
SetText(sLine, iLine++);
}
}
public void SetText(string Text, int Line) // Loop over each line
{ foreach (var sLine in sLines)
short nMemoryPosition = 0x00; // Position at which to write the new string data {
string sSendData = ""; // String data to send // Set the text of this line
byte[] baData; // Byte array of data to send SetText(sLine, line++);
short nDataCount = 0; // Amount of data to send }
}
// Figure out the initial memory position based on the line number public void SetText(string text, int line)
switch (Line) {
{ // Position at which to write the new string data
case 1: short memoryPosition = 0x00;
nMemoryPosition = 0x00;
break;
case 2: // String data to send
nMemoryPosition = 0x40; string sendData;
break;
case 3: // Byte array of data to send
nMemoryPosition = 0x14; byte[] data;
break;
case 4: // Amount of data to send
nMemoryPosition = 0x54; short dataCount = 0;
break;
}
// Pad the text to the right width // Figure out the initial memory position based on the line number
Text = Text.PadRight(m_iWidth); switch (line)
{
case 1:
memoryPosition = 0x00;
break;
// The scratchpad is only 16 bytes long so we need to split it up case 2:
if (m_iWidth > 16) memoryPosition = 0x40;
{ break;
// Select the device
owAdapter.Select(_deviceID);
// Set the data block to just the first 16 characters case 3:
sSendData = Text.Substring(0, 16); memoryPosition = 0x14;
break;
// Initialize the data array case 4:
baData = new byte[18]; memoryPosition = 0x54;
break;
}
// Set the command to write to the scratchpad // Pad the text to the right width
baData[nDataCount++] = 0x4E; text = text.PadRight(_width);
// Set the memory position // The scratchpad is only 16 bytes long so we need to split it up
baData[nDataCount++] = (byte) nMemoryPosition; if (_width > 16)
{
// Select the device
owAdapter.Select(DeviceId);
// Add the text data to the data // Set the data block to just the first 16 characters
foreach (byte bChar in System.Text.Encoding.Default.GetBytes(sSendData)) sendData = text.Substring(0, 16);
baData[nDataCount++] = bChar;
// Set the block // Initialize the data array
owAdapter.SendBlock(baData, nDataCount); data = new byte[18];
// Select the device // Set the command to write to the scratchpad
owAdapter.Select(_deviceID); data[dataCount++] = 0x4E;
// Send the scratchpad data to the LCD // Set the memory position
owAdapter.SendByte(0x48); data[dataCount++] = (byte) memoryPosition;
// Reset the device // Add the text data to the data
owAdapter.Reset(); foreach (var bChar in System.Text.Encoding.Default.GetBytes(sendData))
data[dataCount++] = bChar;
// Increment the memory position // Set the block
nMemoryPosition += 16; owAdapter.SendBlock(data, dataCount);
// Set the data to the rest of the line // Select the device
sSendData = Text.Substring(16, m_iWidth - 16); owAdapter.Select(DeviceId);
}
else
{
// Just set the data string to whatever was passed in
sSendData = Text;
}
// Select the device // Send the scratchpad data to the LCD
owAdapter.Select(_deviceID); owAdapter.SendByte(0x48);
// Initialize the data array // Reset the device
baData = new byte[18]; owAdapter.Reset();
// Reset the data count // Increment the memory position
nDataCount = 0; memoryPosition += 16;
// Set the command to write to the scratchpad // Set the data to the rest of the line
baData[nDataCount++] = 0x4E; sendData = text.Substring(16, _width - 16);
}
else
{
// Just set the data string to whatever was passed in
sendData = text;
}
// Set the memory position // Select the device
baData[nDataCount++] = (byte) nMemoryPosition; owAdapter.Select(DeviceId);
// Add the text data to the data // Initialize the data array
foreach (byte bChar in System.Text.Encoding.Default.GetBytes(sSendData)) data = new byte[18];
baData[nDataCount++] = bChar;
// Set the block // Reset the data count
owAdapter.SendBlock(baData, nDataCount); dataCount = 0;
// Select the device // Set the command to write to the scratchpad
owAdapter.Select(_deviceID); data[dataCount++] = 0x4E;
// Send the scratchpad data to the LCD // Set the memory position
owAdapter.SendByte(0x48); data[dataCount++] = (byte) memoryPosition;
// Reset the device // Add the text data to the data
owAdapter.Reset(); foreach (var bChar in System.Text.Encoding.Default.GetBytes(sendData))
} data[dataCount++] = bChar;
public void Clear() // Set the block
{ owAdapter.SendBlock(data, dataCount);
// Select the device
owAdapter.Select(_deviceID);
// Clear the display // Select the device
owAdapter.SendByte(0x49); 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);
}
}
} }

View File

@@ -5,12 +5,10 @@ namespace OneWireAPI
[Serializable] [Serializable]
public class owException : Exception public class owException : Exception
{ {
#region Enumerations public enum ExceptionFunction
public enum owExceptionFunction
{ {
Access, Access,
CRC, Crc,
ReadBit, ReadBit,
ReadByte, ReadByte,
Select, Select,
@@ -20,19 +18,11 @@ namespace OneWireAPI
SetLevel SetLevel
} }
#endregion
#region Private member variables
private readonly int _errorNumber; private readonly int _errorNumber;
private readonly owExceptionFunction _errorFunction; private readonly ExceptionFunction _errorFunction;
private readonly owIdentifier _deviceID; private readonly owIdentifier _deviceId;
#endregion public owException(ExceptionFunction function, int number)
#region Constructors
public owException(owExceptionFunction function, int number)
{ {
// Store the exception function // Store the exception function
_errorFunction = function; _errorFunction = function;
@@ -41,37 +31,33 @@ namespace OneWireAPI
_errorNumber = number; _errorNumber = number;
} }
public owException(owExceptionFunction function, owIdentifier deviceID) public owException(ExceptionFunction function, owIdentifier deviceId)
{ {
// Store the exception function // Store the exception function
_errorFunction = function; _errorFunction = function;
// Store the device ID // 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 // Store the exception function
_errorFunction = function; _errorFunction = function;
// Store the device ID // Store the device ID
_deviceID = deviceID; _deviceId = deviceId;
// Store the exception number // Store the exception number
_errorNumber = number; _errorNumber = number;
} }
#endregion public owIdentifier DeviceId
#region Properties
public owIdentifier DeviceID
{ {
get { return _deviceID; } get { return _deviceId; }
} }
public owExceptionFunction Function public ExceptionFunction Function
{ {
get { return _errorFunction; } get { return _errorFunction; }
} }
@@ -82,16 +68,26 @@ namespace OneWireAPI
{ {
switch (_errorFunction) switch (_errorFunction)
{ {
case owExceptionFunction.Access: return "Unable to access device"; case ExceptionFunction.Access:
case owExceptionFunction.CRC: return "CRC mismatch"; return "Unable to access device";
case owExceptionFunction.ReadBit: return "Error reading bit"; case ExceptionFunction.Crc:
case owExceptionFunction.ReadByte: return "Error reading byte"; return "CRC mismatch";
case owExceptionFunction.Select: return "Unable to select device"; case ExceptionFunction.ReadBit:
case owExceptionFunction.SendBit: return "Error sending bit"; return "Error reading bit";
case owExceptionFunction.SendBlock: return "Error sending block"; case ExceptionFunction.ReadByte:
case owExceptionFunction.SendByte: return "Error sending byte"; return "Error reading byte";
case owExceptionFunction.SetLevel: return "Error setting level"; case ExceptionFunction.Select:
default: return "Unknown error in function" + _errorFunction; 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; } get { return _errorNumber; }
} }
#endregion
} }
} }

View File

@@ -1,80 +1,65 @@
using System;
using System.Text; using System.Text;
namespace OneWireAPI 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 string _friendlyName; // Friendly display name
private readonly int _familyCode; // Family code private readonly int _familyCode; // Family code
#endregion
#region Constructors
public owIdentifier() public owIdentifier()
{ {
// Create a blank ID // Create a blank ID
_rawID = new short[8]; _rawId = new short[8];
} }
public owIdentifier(byte[] deviceID) public owIdentifier(byte[] deviceId)
{ {
// Create a blank ID // Create a blank ID
_rawID = new short[8]; _rawId = new short[8];
// Copy the byte array to the short array // Copy the byte array to the short array
for (int i = 0; i < deviceID.Length; i++) for (var i = 0; i < deviceId.Length; i++)
_rawID[i] = deviceID[i]; _rawId[i] = deviceId[i];
// Get the friendly name // Get the friendly name
_friendlyName = ConvertToString(_rawID); _friendlyName = ConvertToString(_rawId);
// Get the family code // Get the family code
_familyCode = _rawID[0]; _familyCode = _rawId[0];
} }
public owIdentifier(short[] deviceID) public owIdentifier(short[] deviceId)
{ {
// Store the ID supplied // Store the ID supplied
_rawID = deviceID; _rawId = deviceId;
// Get the friendly name // Get the friendly name
_friendlyName = ConvertToString(_rawID); _friendlyName = ConvertToString(_rawId);
// Get the family code // Get the family code
_familyCode = _rawID[0]; _familyCode = _rawId[0];
} }
#endregion private static string ConvertToString(short[] rawId)
#region Private methods
private static string ConvertToString(short[] rawID)
{ {
StringBuilder friendlyID = new StringBuilder(); var friendlyId = new StringBuilder();
// Loop backwards over the ID array // 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 // 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 the ID string
return friendlyID.ToString(); return friendlyId.ToString();
} }
#endregion public short[] RawId
#region Properties
public short[] RawID
{ {
get { return _rawID; } get { return _rawId; }
} }
public string Name public string Name
@@ -87,15 +72,9 @@ namespace OneWireAPI
get { return _familyCode; } get { return _familyCode; }
} }
#endregion
#region Methods
public override string ToString() public override string ToString()
{ {
return _friendlyName; return _friendlyName;
} }
#endregion
} }
} }

View File

@@ -1,95 +1,76 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owNetwork public class owNetwork
{ {
#region Member variables
private owSession _session; // Current session private owSession _session; // Current session
private Dictionary<string, owDevice> _deviceList; // List of current devices private Dictionary<string, owDevice> _deviceList; // List of current devices
#endregion public owNetwork(owSession session)
#region Constructor
public owNetwork(owSession Session)
{ {
_session = Session; _session = session;
_deviceList = new Dictionary<string, owDevice>(); _deviceList = new Dictionary<string, owDevice>();
} }
#endregion
#region Delegates
public delegate void DeviceEventDelegate(owDevice device); public delegate void DeviceEventDelegate(owDevice device);
#endregion
#region Events
public event DeviceEventDelegate DeviceAdded; public event DeviceEventDelegate DeviceAdded;
#endregion
#region Private methods
private void LoadDevices() private void LoadDevices()
{ {
owDevice device; // Current device object
// Get the first device on the network // 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 // Keep looping while we get good device data
while (nResult == 1) while (nResult == 1)
{ {
// Create a new device ID buffer // Create a new device ID buffer
short[] nROM = new short[8]; var id = new short[8];
// Get the ROM from the device // 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 the ROM was read correctly then add the device to the list
if (nResult == 1) if (nResult == 1)
{ {
// Get the deviceID // Get the deviceID
owIdentifier deviceID = new owIdentifier(nROM); var deviceId = new owIdentifier(id);
// Create a new device object // Create a new device object
switch (deviceID.Family) owDevice device;
switch (deviceId.Family)
{ {
case 0x10: case 0x10:
device = new owDeviceFamily10(_session, nROM); device = new owDeviceFamily10(_session, id);
break; break;
case 0x1D: case 0x1D:
device = new owDeviceFamily1D(_session, nROM); device = new owDeviceFamily1D(_session, id);
break; break;
case 0x20: case 0x20:
device = new owDeviceFamily20(_session, nROM); device = new owDeviceFamily20(_session, id);
break; break;
case 0x26: case 0x26:
device = new owDeviceFamily26(_session, nROM); device = new owDeviceFamily26(_session, id);
break; break;
case 0x12: case 0x12:
device = new owDeviceFamily12(_session, nROM); device = new owDeviceFamily12(_session, id);
break; break;
case 0xFF: case 0xFF:
device = new owDeviceFamilyFF(_session, nROM); device = new owDeviceFamilyFF(_session, id);
break; break;
default: default:
device = new owDevice(_session, nROM); device = new owDevice(_session, id);
break; break;
} }
// Check if we've seen this device before // 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 // Add the device to the device list
_deviceList[device.ID.Name] = device; _deviceList[device.Id.Name] = device;
// Raise the device added event // Raise the device added event
if (DeviceAdded != null) if (DeviceAdded != null)
@@ -102,19 +83,11 @@ namespace OneWireAPI
} }
} }
#endregion
#region Properties
public Dictionary<string, owDevice> Devices public Dictionary<string, owDevice> Devices
{ {
get { return _deviceList; } get { return _deviceList; }
} }
#endregion
#region Public methods
public void Initialize() public void Initialize()
{ {
// Load the device list // Load the device list
@@ -130,7 +103,5 @@ namespace OneWireAPI
// Get rid of the session // Get rid of the session
_session = null; _session = null;
} }
#endregion
} }
} }

View File

@@ -1,13 +1,10 @@
using Common.Debug; using Common.Debug;
using System; using System;
using System.Threading;
namespace OneWireAPI namespace OneWireAPI
{ {
public class owSession public class owSession
{ {
#region Member variables
private int _sessionHandle; // Session handle private int _sessionHandle; // Session handle
private owNetwork _network; // Network object private owNetwork _network; // Network object
@@ -15,35 +12,27 @@ namespace OneWireAPI
private readonly short _portType; // Port type private readonly short _portType; // Port type
private readonly byte[] _stateBuffer; // Global state buffer private readonly byte[] _stateBuffer; // Global state buffer
#endregion
#region Constructor
public owSession() public owSession()
{ {
// Create the global state buffer // 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 // 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); 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 // 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 // Store the port number and type specified
_portNumber = PortNumber; _portNumber = portNumber;
_portType = PortType; _portType = portType;
} }
#endregion
#region Properties
public short PortNumber public short PortNumber
{ {
get { return _portNumber; } get { return _portNumber; }
@@ -69,23 +58,19 @@ namespace OneWireAPI
get { return _stateBuffer; } get { return _stateBuffer; }
} }
#endregion
#region Methods
public bool Acquire() public bool Acquire()
{ {
// Create a byte array to hold the version information // Create a byte array to hold the version information
byte[] version = new byte[80]; var version = new byte[80];
// Get the version // Get the version
TMEX.Get_Version(version); TMEX.Get_Version(version);
// Decode the 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 // 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); Tracer.WriteLine("Version: {0}", sVersion);
@@ -101,7 +86,7 @@ namespace OneWireAPI
return false; return false;
// Setup the port for the current session // Setup the port for the current session
short result = TMEX.TMSetup(_sessionHandle); var result = TMEX.TMSetup(_sessionHandle);
Tracer.WriteLine("TMSetup - Return: {0}", result); Tracer.WriteLine("TMSetup - Return: {0}", result);
@@ -138,7 +123,7 @@ namespace OneWireAPI
} }
// Close the session // Close the session
short result = TMEX.TMClose(_sessionHandle); var result = TMEX.TMClose(_sessionHandle);
Tracer.WriteLine("TMClose - Return: {0}", result); Tracer.WriteLine("TMClose - Return: {0}", result);
@@ -150,7 +135,5 @@ namespace OneWireAPI
// Clear the session variable // Clear the session variable
_sessionHandle = 0; _sessionHandle = 0;
} }
#endregion
} }
} }